user2278906
user2278906

Reputation: 131

python how to check and replace words in string?

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

Answers (3)

marcadian
marcadian

Reputation: 2618

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)

Upvotes: 8

Brandon
Brandon

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

mathematical.coffee
mathematical.coffee

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

Related Questions