替换python中的精确字符串

2024-10-03 11:16:35 发布

您现在位置:Python中文网/ 问答频道 /正文

给出了这个看似简单的字符串替换函数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基础知识。有什么好主意吗


Tags: sample函数字符串innewforresultreplace
2条回答
import re
search_str = 'fl'
my_strings = ['fl', 'florida']
for string in my_strings:
    if re.match(f'^{search_str}$', string):
        print('florida')
    else:
        print(string)

这样你可以更灵活一点

只需检查单词是否与'fl'等价-如果是,则将其转换为'florida'

sample_lst = ['fl', 'florida']
for word in sample_lst:
    new_word = word
    if word == 'fl':
        new_word = 'florida'
    print(new_word)

或者

sample_lst = ['fl', 'florida']
for word in sample_lst:
    new_word = 'florida' if word == 'fl' else word
    print(new_word)

如果您想将结果存储在新列表中,您甚至可以执行列表理解

sample_lst = ['fl', 'florida']
result = ['florida' if word == 'fl' else word for word in sample_lst]

另一方面,如果要检查是否有单词(可以用空格包围),可以使用正则表达式:

import re
sample_lst = ['fl', 'florida']
for word in sample_lst:
    new_word = re.sub(r'\bfl\b', 'florida', word)
    print(new_word)

和列表理解(当然我们需要列表理解):

import re
sample_lst = ['fl', 'florida']
result = [re.sub(r'\bfl\b', 'florida', word) for word in sample_lst]

相关问题 更多 >