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
  • 95
  • 1
  • 7

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
  • 669,327
  • 51
  • 454
  • 560
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
  • 30,962
  • 1
  • 21
  • 47