【问题标题】:Converting a stripped string into an interger?将剥离的字符串转换为整数?
【发布时间】:2013-11-04 02:36:12
【问题描述】:

我正在尝试从所有文本中删除一个字符串并将其转换为一个整数,以便我可以更轻松地在其上使用 if 语句...

示例:

count = "19 Count"
count = count.replace(" Count", "")
print repr(count)
print int(count)

示例输出:

'19'
19

但是在我的实际代码中,我的输出是:

实际输出:

u'19'
Traceback (most recent call last):
  File "C:\test.py", line 153, in <module>
    print int(count)
ValueError: invalid literal for int() with base 10: ''

【问题讨论】:

  • 我已经尝试了代码并且输出是你所期望的
  • 您是否从您的实际代码中的文件中读取?
  • @Christian 就像我在帖子中展示的那样,我的示例输出显示了'19'19,但在我的真实代码中它的显示方式不同。
  • count 的类型是什么?你试过int(repr(count))吗?
  • 我正在使用 python 2.7.3 我复制粘贴了你的代码,它工作正常,为什么会有所不同?

标签: python string python-2.7 replace int


【解决方案1】:

错误ValueError: invalid literal for int() with base 10: '' 的原因是您在int() 中传递了空字符串。喜欢int('')主要问题在于去除非数字字符的代码

正则表达式可用于获取第一个数字。

In [3]: import re

In [4]: a = re.search('\d+', ' 18 count 9 count')

In [5]: int(a.group())
Out[5]: 18

【讨论】:

  • 任何想法:count = "19 Count 1 Count" 我只想要这个例子中的第一组数字,19 当我尝试使用 sub 时,我的号码是 191
【解决方案2】:

检查每个单词的数字,如果为真,则使用Filter 输出。

>>> count = "19 Count"
>>> filter(lambda x:x.isdigit(), count)
'19'

【讨论】:

  • 不需要lambdafilter(str.isdigit, count)。然而这个解决方案只适用于python2,因为在python3中filter总是返回一个可迭代的而不是一个序列(特别是,不是一个与参数相同类型的序列)。
  • @Bakuriu TypeError: descriptor 'isdigit' of 'str' object needs an argument
  • @Hyflex 我添加了解释。我希望它可以帮助你理解。 :)
  • @PuffinGDI 知道如何解决这个问题:count = "19 Count 1 Count",我只想要第一组数字,在这个例子中是 19,其他的都应该丢弃。
  • @Hyflex 如果您收到该错误,则表示您没有正确阅读了我的评论。是filter(str.digit, count) 不是 filter(str.digit(), count)
【解决方案3】:

试试这个,以满足您的要求。只会匹配第一个“数字集”:

import re
regex = re.compile("(\d+)")
r = regex.search("19 Count 1 Count")
print(int(r.group(1)))

输出:

19

您可以在这里试用代码:http://ideone.com/OwbMYm

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-21
    • 2010-12-31
    相关资源
    最近更新 更多