[英]removing non-numeric characters from a string
strings = ["1 asdf 2", "25etrth", "2234342 awefiasd"] #and so on
哪个是最简单的获取[1, 25, 2234342]
?
没有正则表达式模块或类似(^[0-9]+)
表达式怎么办?
new = []
for item in strings:
new.append(int(''.join(i for i in item if i.isdigit())))
print new
[1, 25, 2234342]
可以编写一个辅助函数来提取前缀:
def numeric_prefix(s):
n = 0
for c in s:
if not c.isdigit():
return n
else:
n = n * 10 + int(c)
return n
用法示例:
>>> strings = ["1asdf", "25etrth", "2234342 awefiasd"]
>>> [numeric_prefix(s) for s in strings]
[1, 25, 2234342]
请注意,如果输入字符串没有数字前缀(如空字符串),这将产生正确的输出(零)。
通过Mikel的解决方案,可以编写更简洁的numeric_prefix定义:
import itertools
def numeric_prefix(s):
n = ''.join(itertools.takewhile(lambda c: c.isdigit(), s))
return int(n) if n else 0
正则表达式的基本用法:
汇入
字符串= [“ 1asdf”,“ 25etrth”,“ 2234342 awefiasd”]
正则表达式= re.compile('^(\\ d *)')
对于s中的字符串:
mo = regex.match(s)
print s, '->', mo.group(0)
1个ASDF-> 1
25etrth-> 25
2234342令人敬畏的-> 2234342
因此,您只想要开头的数字? 而您想避免使用正则表达式? 可能有些短,但这是显而易见的解决方案。
nlist = []
for s in strings:
if not s or s[0].isalpha(): continue
for i, c in enumerate(s):
if not c.isdigit():
nlist.append(int(s[:i]))
break
else:
nlist.append(int(s))
在sahhhm的答案的基础上,您可以使用takewhile
来解决“ 1 asdf 1”问题。
from itertools import takewhile
def isdigit(char):
return char.isdigit()
numbers = []
for string in strings:
result = takewhile(isdigit, string)
resultstr = ''.join(result)
if resultstr:
number = int(resultstr)
if number:
numbers.append(number)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.