0

I am trying to replace any i's in a string with capital I's. I have the following code:

str.replace('i ','I ')

However, it does not replace anything in the string. I am looking to include a space after the I to differentiate between any I's in words and out of words.

Thanks if you can provide help!

The exact code is:

new = old.replace('i ','I ')
new = old.replace('-i-','-I-')
8
  • 5
    replace doesn't mutate the string in place. You have to assign the replaced string to the variable. Commented Mar 27, 2014 at 19:59
  • Oh sorry. My exact code is: Commented Mar 27, 2014 at 20:00
  • 1) Make sure to look at the value in new, not old? 2) What is the actual input and the actual output for each case? (Surely not every case doesn't change anything!) Commented Mar 27, 2014 at 20:04
  • My old string has several I's throughout which are lowercase. I am basically trying to make them uppercase. Commented Mar 27, 2014 at 20:04
  • The string is part of Green eggs and ham by Dr Seuss, I believe. 'i am sam\nsam I am\nThat Sam-i-am!' Commented Mar 27, 2014 at 20:06

2 Answers 2

2
new = old.replace('i ','I ')
new = old.replace('-i-','-I-')

You throw away the first new when you assign the result of the second operation over it.

Either do

new = old.replace('i ','I ')
new = new.replace('-i-','-I-')

or

new = old.replace('i ','I ').replace('-i-','-I-')

or use regex.

Sign up to request clarification or add additional context in comments.

Comments

1

I think you need something like this.

>>> import re
>>> s = "i am what i am, indeed."
>>> re.sub(r'\bi\b', 'I', s)
'I am what I am, indeed.'

This only replaces bare 'i''s with I, but the 'i''s that are part of other words are left untouched.

For your example from comments, you may need something like this:

>>> s = 'i am sam\nsam I am\nThat Sam-i-am! indeed'
>>> re.sub(r'\b(-?)i(-?)\b', r'\1I\2', s)
'I am sam\nsam I am\nThat Sam-I-am! indeed'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.