Search and Replace in Strings


question2 = question.replace("swallow", \     "European swallow") question3 = question.replace("swallow", \     "African swallow")

The native string type in Python provides a replace(old, new, maxreplace) method to replace a specific substring with new text. The replace method accepts a search string as the first argument and replacement string as the second argument. Each occurrence of the search string will be replaced with the new string. Optionally, you can specify a maximum number of times to perform the replace operation as the third argument.

question = "What is the air speed velocity of \     an unlaiden swallow?" print question question2 = question.replace("swallow", \     "European swallow") print question2 question3 = question.replace("swallow", \     "African swallow") print question3


replace_str.py

What is the air speed velocity of an unlaiden swallow? What is the air speed velocity of an unlaiden European swallow? What is the air speed velocity of an unlaiden African swallow?


Output from replace_str.py code



Python Phrasebook(c) Essential Code and Commands
Python Phrasebook
ISBN: 0672329107
EAN: 2147483647
Year: N/A
Pages: 138
Authors: Brad Dayley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net