简体   繁体   中英

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

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)

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

eg

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".

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM