V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
Zhepro
V2EX  ›  Python

复制出来四个数字中间带换行,怎么用 Python 处理呢?

  •  
  •   Zhepro · 2020-05-30 13:58:21 +08:00 · 1928 次点击
    这是一个创建于 1399 天前的主题,其中的信息可能已经有所发展或是发生改变。
    复制到代码里还是换行运行不了,怎么把换行去掉四个数字相加?
    Sanko
        1
    Sanko  
       2020-05-30 14:07:10 +08:00
    给个例子
    Zhepro
        2
    Zhepro  
    OP
       2020-05-30 14:12:01 +08:00
    @Sanko
    print(splitss('66
    82
    124
    125'))
    就是我从网页复制四个数字到代码里就是上面这样自带换行,实际上应该怎么处理呢,就是把换行去掉相加
    tom8
        3
    tom8  
       2020-05-30 14:21:14 +08:00
    def splitss(str):
    sum = 0
    for i in str.split('\n'):
    sum += int(i)
    return sum
    ipwx
        4
    ipwx  
       2020-05-30 14:24:32 +08:00
    S = '''66
    82
    124
    125'''

    print(sum(map(int, S.split('\n'))))
    ----

    话说但凡看完了 Python 教程都不至于不会写这个吧?
    Zhepro
        5
    Zhepro  
    OP
       2020-05-30 14:27:01 +08:00
    @ipwx 。。。小白,没想到这条
    Zhepro
        6
    Zhepro  
    OP
       2020-05-30 14:27:11 +08:00
    @tom8 谢谢,搞定了
    yucongo
        7
    yucongo  
       2020-05-30 16:45:26 +08:00
    sum(int(elm) for elm in S.split())

    sum(int(elm) for elm in re.findall(r'\d+', S))
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2883 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 11:20 · PVG 19:20 · LAX 04:20 · JFK 07:20
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.