如何从字符串中删除数字?
这对你的情况有作用吗?
>>> s = '12abcd405'
>>> result = ''.join([i for i in s if not i.isdigit()])
>>> result
'abcd'
这里使用了列表推导式,这里发生的情况与以下结构类似:no_digits = []
# Iterate through the string, adding non-numbers to the no_digits list
for i in s:
if not i.isdigit():
no_digits.append(i)
# Now join all elements of the list with '',
# which puts all of the characters together.
result = ''.join(no_digits)
正如 @AshwiniChaudhary 和 @KirkStrauser 所指出的那样,您实际上不需要在一行代码中使用方括号,可以将括号内的部分变为生成器表达式(比列表推导式更高效)。 即使这不符合您任务的要求,也应该 eventually 了解一下 :):
>>> s = '12abcd405'
>>> result = ''.join(i for i in s if not i.isdigit())
>>> result
'abcd'
[]
。 - Ashwini Chaudharys.translate
比列表推导式快约 10 倍(在 Python 2.7 中测试)。提醒一下后来阅读此内容的人。 - Patrick还有一个常被忽略的选项是str.translate
,它比循环/正则表达式的方法更快:
对于 Python 2:
from string import digits
s = 'abc123def456ghi789zero0'
res = s.translate(None, digits)
# 'abcdefghizero'
对于 Python 3:
from string import digits
s = 'abc123def456ghi789zero0'
remove_digits = str.maketrans('', '', digits)
res = s.translate(remove_digits)
# 'abcdefghizero'
'abc123def456ghi789zero0'.translate({ord(k): None for k in digits})
(该方法可以从字符串中删除数字) - valignatev不确定您的老师是否允许您使用过滤器,但是...
"".join(filter(lambda x: x.isalpha(), "a1a2a3s3d4f5fg6h"))
返回-
'aaasdffgh'
比循环更高效...
例子:
for i in range(10):
a.replace(str(i),'')
"".join(filter(lambda x: x.isalpha(), "a1a2a3s3d4f5fg6h"))
来获得一个字符串。这里的初始字符串是空字符串。 - rodrigolece仅列出几个(其他人已经提出了一些)
方法1:
''.join(i for i in myStr if not i.isdigit())
方法二:
def removeDigits(s):
answer = []
for char in s:
if not char.isdigit():
answer.append(char)
return ''.join(answer)
''.join(filter(lambda x: not x.isdigit(), mystr))
方法四:
nums = set(map(int, range(10)))
''.join(i for i in mystr if i not in nums)
方法五:
''.join(i for i in mystr if ord(i) not in range(48, 58))
''.join(answer)
而不是''.join(char)
。 - Sreramout_string = filter(lambda c: not c.isdigit(), in_string)
<filter object at 0x7f749e1745c0>
。 Python3.6。 - TitanFighter假设st是您未格式化的字符串,则运行
st_nodigits=''.join(i for i in st if i.isalpha())
l = ['0','1','2','3','4','5','6','7','8','9']
st_res=""
for ch in s:
if ch not in l:
st_res+=ch
我希望使用正则表达式来完成这个任务,但由于只能使用列表、循环、函数等方法...
以下是我想到的方法:
stringWithNumbers="I have 10 bananas for my 5 monkeys!"
stringWithoutNumbers=''.join(c if c not in map(str,range(0,10)) else "" for c in stringWithNumbers)
print(stringWithoutNumbers) #I have bananas for my monkeys!
re
模块进行字符串操作:result = re.sub(r'[0-9]+', '', s)
,意为将字符串中的所有数字替换为空字符串。 - Wiktor Stribiżewresult = re.sub(r"\d+", "", s)
。速度可能取决于所使用的具体字符串,但对我而言,re.sub
的速度大约是str.translate
的两倍(如果不使用预编译的模式,则略微慢一些)。 - Nathanre.sub(r'[0-9]+', '', s)
删除 找到的匹配项(请注意第二个参数是一个空字符串),它不能添加任何内容。请检查您的代码。 - Wiktor Stribiżew