0

I am trying to capitalize all occurrences of the word 'I' - not letter 'i'.

Input: this is my input, how do i do capitalize the word i?

Expected: this is my input, how do I do capitalize the word I?

I have tried a simple .replace('i', 'I') but obviously that doesn't work.

user572780
  • 257
  • 3
  • 10

2 Answers2

1

Use a regular expression, and match i with word boundaries \b on both sides.

import re

output_string = re.sub(r'\bi\b', 'I', input_string)
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

Use regex with word bounds surrounding "i" to replace it:

import re

re.sub(r"\bi\b", "I", "this is my input, how do i do capitalize the word i?")
# outputs "this is my input, how do I do capitalize the word I?"

Read here for more info on what a word bound is.

Aplet123
  • 33,825
  • 1
  • 29
  • 55