我有以下格式的字符串:替换一些前缀开头的所有字符串
str = "1:20 2:25 3:0.432 2:-17 10:12"
我想例如更换所有字符串的开始"2:"
到"2:0"
,从而有:
str = "1:20 2:0 3:0.432 2:0 10:12"
的replace
功能是不够的,因为它会导致
str.replace("2:", "2:0") = "1:20 2:025 3:0.432 2:0-17 10:12"
是否有Python功能?
我有以下格式的字符串:替换一些前缀开头的所有字符串
str = "1:20 2:25 3:0.432 2:-17 10:12"
我想例如更换所有字符串的开始"2:"
到"2:0"
,从而有:
str = "1:20 2:0 3:0.432 2:0 10:12"
的replace
功能是不够的,因为它会导致
str.replace("2:", "2:0") = "1:20 2:025 3:0.432 2:0-17 10:12"
是否有Python功能?
一种解决方案是使用正则表达式:
import re
new_str = re.sub('2:-?\d+', '2:', '1:20 2:25 3:0.432 2:-17 10:12')
另外,如果你的字符串格式始终保证是像你给(用空格隔开,每个项目)的例子,你可以放弃使用正则表达式和使用列表理解:
new_str = ' '.join(['2:0' if s.startswith('2:') else s for s in old.split(' ')])
您可以通过使用str.startswith
和str.split
完成你的任务:
s = "1:20 2:25 3:0.432 2:-17 10:12"
print(" ".join(["2:0" if ch.startswith("2:") else ch for ch in s.split()]
输出:,
1:20 2:0 3:0.432 2:0 10:12
ch.startswith("2:")
检查分割后的各子,看它是否与"2:"
开始如果是这样,我们更换与"2:0"
其他我们只是保持原始子字符串调用str.join
重新加入字符串。
您可以使用re.sub:
import re
s = "1:20 2:25 3:0.432 2:-17 10:12"
print re.sub("2:-?\d+", "2:0", s)
请注意str
是一个关键字(类型),您应该避免阴影,请将您的字符串命名为s
或string
或类似的东西。
sep = ' ' # you can change the character which separates your values here
s = "1:20 2:25 3:0.432 2:-17 10:12"
values = s.split(sep) # get the sep separated strings
new_values = []
for v in values:
if v[0] == '2':
new_values.append('2:0') # change the ones which start with 2
else:
new_values.append(v) # keep the others
result = sep.join(new_values) # rejoin the values in a string
附录:如果你特别希望确保字符串中,你正在改变以“2:”而不是检查它是否只能与“2”开始,因为我已经做了,你可以使用if v[:2] == '2:'
或在其他答案中指出了startswith
。 以上代码的较短版本是:
sep = ' '
s = '1:20 2:25 3:0.432 2:-17 10:12'
s = sep.join([v if v[:2] != '2:' else '2:0' for v in s.split(sep)])
你是对的,编辑。 –
正则表达式可能是您想要探索的模块。在您的当前任务的情况下,像下面这样就足够了:
rawstr = "1:20 2:25 3:0.432 2:-17 10:12"
newstr = re.sub("2:\S+", "2:0", rawstr)
应中newstr等于 '1:20 2:0 3:0.432 2:0 10:12'。这是因为正则表达式将'2:'之后的1个非空白字符替换为'2:0'。我强烈建议你探索的正则表达式HOWTO它提供的这些功能优异的描述:
l = str.split(' ')
l2 = []
for s in l:
if s.startswith('2:'):
s = '2:0'
l2.append(s)
new_str = ' '.join(l2)
@PM 2Ring,感谢您的编辑 – ypx
你有没有考虑使用正则表达式? – rlms
在附注中,如果使用'str'作为变量名称,则会遇到错误,因为它是内置类型。 – rlms