0

I'm trying to use the count and replace string methods to count and then replace (more so remove) specific singular characters (ex, 'a' by itself) or words (ex, 'the'), but not every instance of that character. (ex, I do not want to replace a with nothing, and cause the word character to become chrcter)

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

I know this isn't really necessary, but I just wanted to find out how many instances of a I needed to replace with the replace call.

print(my_string.count('a')) 

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

print(my_string)

so clearly here I'm hoping that it would just remove the lone a's, but as indicated by the returned count number, and actually running the program, it simply removes all of the a characters from the program.

nagataaaas
  • 400
  • 2
  • 13
spence
  • 1
  • Does this answer your question? [Python - Replace only exact word in string](https://stackoverflow.com/questions/60237488/python-replace-only-exact-word-in-string) – Abdul Aziz Barkat Feb 25 '23 at 03:40
  • [Formatting help](https://stackoverflow.com/editing-help)... [Formatting sandbox](https://meta.stackexchange.com/questions/3122/formatting-sandbox) – wwii Feb 25 '23 at 04:44

3 Answers3

0

You add spaces/punctuation around the pattern you want to remove.

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

Result:

'This a sentence.'
0

If you want to replace isolated instances of the word "a" and not just instances of the letter, one way to do this is to see if each instance of "a" is surrounded by letters, punctuation, spaces, etc.

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_list:
    new_string += char

print(new_string)  # String with "a" removed.
BappoHotel
  • 52
  • 10
0

Please note that this also removes the punctuation after the words. If you do not want this, remove the + 1 from line 28.

def replace_words(string: str, old: str, new: str) -> str:
    """Replaces all instances of the specified *word* in the sentence."""

    CHARS = [",", ".", "!", "?", " "]  # The characters that separate words

    indexes = []
    string = [char for char in string]  # Convert the string into a list of characters.
    new = [item for item in new]

    for i in range(len(string)):
        for i2 in range(len(old)):  # Compare to check for a match.
            if string[i + i2] != old[i2]:  # Character does not match.
                break
        else:
            if i != 0:  # First character in the string.
                if string[i - 1] not in CHARS:  # Not a punctuation denoting character.
                    continue

            if i != len(string) - 1:  # Last character in the string.
                if string[i + 1] not in CHARS:
                    continue

            indexes.append((i, i + len(old)))  # Add the index to the list to remove.

    for index in indexes[
        ::-1
    ]:  # Reverse the list using slicing. Not reversing the list order would cause the indexes to shift.
        string[index[0] : index[1] + 1] = new

    return "".join(string)  # Join the list back into a string.


print(
    replace_words(
        "a and the and a character and something but not a something else.", "a", ""
    )
)
skifli
  • 11
  • 1
  • 4