给出了这个看似简单的字符串替换函数python
sample_str = 'fl'
print(sample_str.replace('fl','florida')
result: 'florida'
但是,如何避免这种结果:
sample_lst = ['fl', 'florida']
for word in sample_lst:
new_word = word.replace('fl', 'florida')
print(new_word)
'florida'
'floridaorida'
重点是,我有一个大熊猫df,我试图替换像“fl”这样的东西,但只有当“fl”单独出现在字符串中时,而不是当它作为其他字符串的一部分出现时,如“florida”或“nfl”等
我尝试使用像这样的正则表达式字符串r'fd(?![0 | |]')。那没用。这似乎是一个基本的问题,所以我想我忽略了一些早已丢失在我记忆中的python基础知识。有什么好主意吗
这样你可以更灵活一点
只需检查单词是否与
'fl'
等价-如果是,则将其转换为'florida'
:或者
如果您想将结果存储在新列表中,您甚至可以执行列表理解
另一方面,如果要检查是否有单词(可以用空格包围),可以使用正则表达式:
和列表理解(当然我们需要列表理解):
相关问题 更多 >
编程相关推荐