如何替换单个字符或单词的独立实例

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

我正在尝试使用计数和替换字符串方法来计数然后替换(更多的是删除)特定的单数字符(例如,'a'本身)或单词(例如,'the'),但不是每个实例那个角色。 (例如,我不想将 a 替换为空,并导致单词 character 变成 chrcter)

my_string = 'a and the and a character and something but not a something else.'

我知道这不是必需的,但我只是想知道我需要用 replace 调用替换多少个 a 实例。

print(my_string.count('a'))

my_string = my_string.replace('a', '', 8)

打印(我的字符串)

很明显,我希望它只删除单独的 a,但正如返回的计数所示,并且实际运行程序时,它只是从程序中删除所有 a 字符。

python
2个回答
0
投票

如果您想替换单词“a”的孤立实例而不仅仅是字母实例,一种方法是查看“a”的每个实例是否都被字母、标点符号、空格等包围

characters = [",", " ", "."]  # add as many as you desire
my_string = "Hello! I am a person."

character_list = [char for char in my_string]  # makes every character in my_string a string in this list.
remove_indicies = []  # list of indicies to remove

for x in range(len(character_list))
    if character_list[x] == "a":
        if character_list[x-1] in characters and character_list[x+1] in characters:  # if the characters around the "a" are in character_list
            remove_indicies.append(x)

for i in remove_indicies:
    character_list.pop(x)

new_string = ""
for char in character_string:
    new_string += char

print(new_string)  # String with "a" removed.

0
投票

您在要删除的模式周围添加空格/标点符号。

s = "This is a sentence."
s.replace(" is "," ")
s.replace(" is."," ")
s.replace(" is,"," ")
s.replace(" is!"," ")

结果:

'This a sentence.'
© www.soinside.com 2019 - 2024. All rights reserved.