We can use various methods to change the data in a string. We touched on slicing and concatenation earlier in the article, and I am going to talk about it just a little more here. Before, we replaced an entire word; this time we will only replace part of a word: speech='A toast, to bread, whom without there would be no taste' what='No wait that is not right' print speech print what speech=speech[0:51] + 'oa' + speech[52:54] print speech Which would produce the following output: A toast, to bread, whom without there would be no taste No wait that is not right A toast, to bread, whom without there would be no toast We could also use the replace method, which might prove to be a little easier: speech='A toast, to bread, whom without there would be no taste' what='No wait that is not right' print speech print what speech=speech.replace('taste','toast') print speech Resulting in: A toast, to bread, whom without there would be no taste No wait that is not right A toast, to bread, whom without there would be no toast This would also be handy if, say, a certain writer by the name of James Payne began dating your mother: oldFather='Your father is named...whatshisname...' print oldFather oldFather=oldFather.replace('whatshisname', 'James Payne the new Hawtness') print oldFather And the shocking results: Your father is named...whatshisname... Your father is named...James Payne the new Hawtness...
blog comments powered by Disqus |
|
|
|
|
|
|
|