Reputation: 131
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
Upvotes: 0
Views: 3410
Reputation: 2618
create a dictionary mapping and iterate over it, something like this
d = {"I": "You", "I'm": "You're".....}
for k,v in d.iteritems():
statement = statement.replace(k, v)
d = {"I": "You", "I'm": "You're".....}
for k,v in d.items():
statement = statement.replace(k, v)
Upvotes: 8
Reputation: 284
This has been asked many, many times before. You'll want to use some variation of the replace
method from Python's Standard Library.
Upvotes: 1
Reputation: 56915
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".
Upvotes: 2