'How to convert a letter to lowercase after a quotation mark?

How to convert a letter to lowercase which is in a string after a quotation mark?

Like this:

"Trees Are Never Sad Look At Them Every Once In Awhile They'Re Quite Beautiful."

should become

"Trees Are Never Sad Look At Them Every Once In Awhile They're Quite Beautiful."


Solution 1:[1]

You can loop through the string and then find the character of the apostrophe. Then replace the upper case letter with lowercase letter following the apostrophe:

string = "Trees Are Never Sad Look At Them Every Once In Awhile They'Re Quite Beautiful."

for i in range(len(string)):
    if string[i] == "'": # Check for apostrophe
        string = string.replace(string[i+1], string[i+1].lower()) # Make the character followed by apostrophe lower case by replacing uppercase letter.
print(string)

Output:

Trees Are Never Sad Look At Them Every Once In Awhile They're Quite Beautiful.

Solution 2:[2]

Using re.sub with a callback function we can try:

import re

inp = "Trees Are Never Sad Look At Them Every Once In Awhile They'Re Quite Beautiful."
output = re.sub(r"'([A-Z])", lambda m: "'" + m.group(1).lower(), inp)
print(output)

This prints:

Trees Are Never Sad Look At Them Every Once In Awhile They're Quite Beautiful.

Solution 3:[3]

Here is another way to do so using join():

data = "Trees Are Never Sad Look At Them Every Once In Awhile They'Re Quite Beautiful."

new_data = "".join(char.lower() if i and data[i-1] == "'" else char for i, char in enumerate(data))
print(new_data)  # Trees Are Never Sad Look At Them Every Once In Awhile They're Quite Beautiful.

Explanation

  • We use enumerate() to iterate over each character in the string, knowing its index.
  • For each character, we check if the previous one is ' using data[i-1] == "'".
  • We also check that it is not the first character of the string, in which case data[i-1] would correspond to the last letter of the string (data[-1]).

We therefore convert the character to lowercase only if the two conditions are met:

  • i != 0, it can also be written if i, because an integer evaluates to True only if it is non-zero.
  • data[i-1] == "'"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Abhyuday Vaish
Solution 3