Two ways to replace python strings

  • 2020-04-02 14:26:50
  • OfStack

Python string substitution is a common problem encountered when python manipulates strings. Here is a brief introduction to the method of string substitution.

Python string substitution can be implemented in two ways:
One is using the string itself.
Replace the string with regularness

Here's an example:
A = 'hello word'
Replace word in string a with python

1. Use the replace method of the string itself


a.replace('word','python')

The output is hello python

2. Complete the substitution with regular expressions:


import re
strinfo = re.compile('word')
b = strinfo.sub('python',a)
print b

The output is also hello python

As for which method to use, depends on your own choice.


Related articles: