Fre*_*ind 25 python string replace
我想替换python字符串末尾的字符.我有这个字符串:
s = "123123"
Run Code Online (Sandbox Code Playgroud)
我想,以取代过去2
用x
.假设有一个方法叫做replace_last
:
r = replace_last(s, '2', 'x')
print r
1231x3
Run Code Online (Sandbox Code Playgroud)
有没有内置或简单的方法来做到这一点?
Miz*_*zor 35
这正是rpartition
函数用于:
rpartition(...)S.rpartition(sep) - >(head,sep,tail)
Run Code Online (Sandbox Code Playgroud)Search for the separator sep in S, starting at the end of S, and return the part before it, the separator itself, and the part after it. If the separator is not found, return two empty strings and S.
我写了这个函数,展示了如何rpartition
在你的用例中使用:
def replace_last(source_string, replace_what, replace_with):
head, _sep, tail = source_string.rpartition(replace_what)
return head + replace_with + tail
s = "123123"
r = replace_last(s, '2', 'x')
print r
Run Code Online (Sandbox Code Playgroud)
输出:
1231x3
Run Code Online (Sandbox Code Playgroud)
小智 24
re.sub
替换字符串末尾的单词import re
s = "123123"
s = re.sub('23$', 'penguins', s)
print s
Run Code Online (Sandbox Code Playgroud)
打印:
1231penguins
Run Code Online (Sandbox Code Playgroud)
要么
import re
s = "123123"
s = re.sub('^12', 'penguins', s)
print s
Run Code Online (Sandbox Code Playgroud)
打印:
penguins3123
Run Code Online (Sandbox Code Playgroud)
这是少数几个没有左右版本的字符串函数之一,但我们可以使用一些字符串函数来模仿行为.
>>> s = '123123'
>>> t = s.rsplit('2', 1)
>>> u = 'x'.join(t)
>>> u
'1231x3'
Run Code Online (Sandbox Code Playgroud)
要么
>>> 'x'.join('123123'.rsplit('2', 1))
'1231x3'
Run Code Online (Sandbox Code Playgroud)
>>> s = "aaa bbb aaa bbb"
>>> s[::-1].replace('bbb','xxx',1)[::-1]
'aaa bbb aaa xxx'
Run Code Online (Sandbox Code Playgroud)
第二个例子
>>> s = "123123"
>>> s[::-1].replace('2','x',1)[::-1]
'1231x3'
Run Code Online (Sandbox Code Playgroud)
当想要的匹配位于字符串末尾时,re.sub
就会出现。
>>> import re
>>> s = "aaa bbb aaa bbb"
>>> s
'aaa bbb aaa bbb'
>>> re.sub('bbb$', 'xxx', s)
'aaa bbb aaa xxx'
>>>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
41130 次 |
最近记录: |