0

I'm new to python and I'm trying to make a function which is able to detect if a string has the words "I", "I'm", "My", "Was", "Our", "me" replace it with "You", "You're", "Your", "Were", "Your" and "You" and also add a question mark at the end if it did not end with any punctuation. So far I have the code

if ' ' in statement and statement[-1].isalpha() is True:
       response = statement
       response = response + "?"

       return response

but I'm not sure how to make the function seach for those words and replace with their opposites. For example if the statement was "My dog said I'm happy" its response should be "Your dog said you're happy?"

thanks

user2278906
  • 121
  • 5
  • 7
  • 12

3 Answers3

8

create a dictionary mapping and iterate over it, something like this

Python 2

d = {"I": "You", "I'm": "You're".....}
for k,v in d.iteritems():
    statement = statement.replace(k, v)

Python 3

d = {"I": "You", "I'm": "You're".....}
for k,v in d.items():
    statement = statement.replace(k, v)
marcadian
  • 2,608
  • 13
  • 20
2

Check out python's replace function, which replaces in a string...

e.g.

x = "My dog said I'm happy"
x.replace("My", "Your") # "Your dog said I'm happy"

You could make a list of old being the list of words to replace and a list new being what to replace with, and then successively replace.

Note that you should replace longer words before shorter words.

For example if you replace "I" with "You" in the above, you'll get "Your dog said You'm happy". Hence you should replace "I'm" before "I".

mathematical.coffee
  • 55,977
  • 11
  • 154
  • 194
1

This has been asked many, many times before. You'll want to use some variation of the replace method from Python's Standard Library.

Community
  • 1
  • 1
Brandon
  • 284
  • 2
  • 7