Obc*_*ure 41 python python-3.x python-3.3
我被赋予了从文本文件或字符串中删除所有非数字字符(包括空格)的任务,然后在旧字符旁边打印新结果,例如:
之前:
sd67637 8
Run Code Online (Sandbox Code Playgroud)
后:
sd67637 8 = 676378
Run Code Online (Sandbox Code Playgroud)
由于我是初学者,我不知道从哪里开始这项任务.请帮忙
小智 69
最简单的方法是使用正则表达式
import re
a = 'lkdfhisoe78347834 (())&/&745 '
result = re.sub('[^0-9]','', a)
print result
>>> '78347834745'
Run Code Online (Sandbox Code Playgroud)
Jon*_*nts 18
循环遍历字符串,char by char并且只包含数字:
new_string = ''.join(ch for ch in your_string if ch.isdigit())
Run Code Online (Sandbox Code Playgroud)
或者在你的字符串上使用正则表达式(如果在某些时候你想分别处理非连续的组)...
import re
s = 'sd67637 8'
new_string = ''.join(re.findall(r'\d+', s))
# 676378
Run Code Online (Sandbox Code Playgroud)
然后print他们出去了:
print(old_string, '=', new_string)
Run Code Online (Sandbox Code Playgroud)
Inb*_*ose 10
有一个内置的.
string.translate(s,table [,deletechars])
删除deletechars中的所有字符(如果存在),然后使用表转换字符,该表必须是256个字符的字符串,为每个字符值提供转换,并按其序号索引.如果table为None,则仅执行字符删除步骤.
>>> import string
>>> non_numeric_chars = ''.join(set(string.printable) - set(string.digits))
>>> non_numeric_chars = string.printable[10:] # more effective method. (choose one)
'sd67637 8'.translate(None, non_numeric_chars)
'676378'
Run Code Online (Sandbox Code Playgroud)
或者你可以没有导入(但没有理由):
>>> chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
>>> 'sd67637 8'.translate(None, chars)
'676378'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
46999 次 |
| 最近记录: |