【问题标题】:Python parse int from stringPython从字符串解析int
【发布时间】:2016-06-29 20:18:28
【问题描述】:
test1 = 'name1'
test2 = 'name2'
..
test3 = 'name45'
test4 = 'name1231231'

假设我有一堆以 'name' 开头的字符串,后跟任意长度的数字。

如何解析字符串中的数字?

regex 是唯一的方法还是有内置模块可以完成这项任务?

【问题讨论】:

  • 我没有投反对票,但您的帖子可能因为其中一个reasons而被投反对票
  • 遍历所有这些,替换 name 并在它们上投射 int()float()
  • int_testi=int(testi[4:len(testi)]) 可以。
  • 它很清楚,并且通过正则表达式进行研究,它怎么没有用处?这可能对其他人有帮助
  • 如果你有这样的字符串 test=['name1','name2','name123125'] 你可以得到这样的整数:ints = [int(n[4:]) for n in test]

标签: python


【解决方案1】:

在 Python 3 中,您可以执行以下操作:

import string

for test in ['name1', 'name2', 'name45', 'name1231231', '123test']:
    print(int(test.strip(string.ascii_letters)))

给你:

1
2
45
1231231
123

string.ascii_letters 给你一个包含所有大写和小写字母的字符串。 Python 的strip() 函数接受一个字符串,指定要删除的字符集,在这种情况下,所有字符都是字母字符,因此只留下数字。

注意:这不适用于123name456 等字符串。

【讨论】:

    【解决方案2】:

    如果您知道前缀是 name,那么您可以只删除该字符串,也可以跳过前四个字母,如下所示:

    s = 'name123'
    print int(s.replace('name',''))
    
    s = 'name123'
    print int(s[4:])
    

    【讨论】:

      猜你喜欢
      • 2011-05-25
      • 1970-01-01
      • 2011-09-11
      • 2021-10-29
      • 1970-01-01
      • 2013-08-12
      • 1970-01-01
      • 2017-09-26
      • 2011-06-25
      相关资源
      最近更新 更多