如何从字符串[python]中删除一次字符?

问题描述 投票:0回答:2

还有比我现在做的更好的方法吗?

word = "baab"
word = word[:word.find('a')]+word[word.find('a')+1:]
print word #bab
python string replace
2个回答
7
投票
In[3]: "baab".replace('a', '', 1)
Out[3]: 'bab'

将仅替换

a
一次,什么都没有,因此将其删除。


5
投票

您可以使用最大计数的字符串替换功能:

s = s.replace('a','',1)

如以下文字记录所示:

>>> s = "baab"
>>> s = s.replace('a','',1)
>>> s
'bab'

来自文档

str.replace(旧,新[,计数])

返回字符串的副本,其中所有出现的子字符串

old
均替换为
new
。如果给出了可选参数
count
,则仅替换第一个
count
出现的位置。

© www.soinside.com 2019 - 2024. All rights reserved.