替换Python中的字符串
我有一个字符串:替换Python中的字符串,python,string,replace,str-replace,Python,String,Replace,Str Replace,我有一个字符串: string = '17 121221 17 17939 234343 17 39393' 如何确保在使用string.replace('17','sth')时只替换17(而不是17939中的17) 我想要一个输出字符串,如: string = 'sth 121221 sth 17939 234343 sth 39393' 干杯, Kate您可以使用regex实现这一点: import re string = '17 121221 17 17939 234343 17 3
string = '17 121221 17 17939 234343 17 39393'
如何确保在使用string.replace('17','sth')时只替换17(而不是17939中的17)
我想要一个输出字符串,如:
string = 'sth 121221 sth 17939 234343 sth 39393'
干杯,
Kate您可以使用
regex
实现这一点:
import re
string = '17 121221 17 17939 234343 17 39393'
>>> print re.sub(r'(\D|^)17(\D|$)', r'\1sth\2', string)
sth 121221 sth 17939 234343 sth 39393
您可以使用
regex
:
import re
string = '17 121221 17 17939 234343 17 39393'
>>> print re.sub(r'(\D|^)17(\D|$)', r'\1sth\2', string)
sth 121221 sth 17939 234343 sth 39393
更易于使用和防故障:
>>> string = '17 121221 17 17939 234343 17 39393'
>>> ' '.join( 'sth' if i == '17' else i for i in string.split() )
'sth 121221 sth 17939 234343 sth 39393'
当简单的
拆分/联接
就足够时,不应使用正则表达式。更易于使用和防故障:
>>> string = '17 121221 17 17939 234343 17 39393'
>>> ' '.join( 'sth' if i == '17' else i for i in string.split() )
'sth 121221 sth 17939 234343 sth 39393'
当简单的
拆分/联接
足够时,不应使用正则表达式。@RajeshKumar,这在123 345 12317 1234中失败,因为它还替换了OP没有替换的12317中的17want@sshashank124如果我使用string.replace('17','sth'),它实际上是有效的!但是,如果17岁处于世界的起点和终点,这将失败string@RajeshKumar,这与123345123171234失败,因为它也替换了12317中的17,而OP没有want@sshashank124如果我使用string.replace('17','sth'),它实际上是有效的!但是如果字符串的开头和结尾都是17,则该操作将失败当字符串中有数字“-17”时,以及在其他一些情况下,该操作将失败。当字符串中有数字“-17”时,以及在其他一些情况下,该操作将失败。