Replace strings in Python (replace, translate | Re search and replace
![Replace strings in Python (replace, translate](https://i.imgur.com/axBPWDg.jpg)
InPython,youcanreplacestringsusingthereplace()andtranslate()methods,ortheregularexpressionfunctions,re.sub()andre.subn().Youcanalsoreplacesubstringsatspecifiedpositionsusingslicing.Youcanalsoremoveasubstringbyreplacingitwithanemptystring().Forextractingsubstringsorfindingtheirpositions,seethefollowingarticles.Therearealsomethodstoconvertbetweenuppercaseandlowercaseletters.Ifyouwanttoreplacethecontentsofatextfile,readthefileasastring,processit,andsaveitagain.Replacesubstringsinastring:replace...
![Replace strings in Python (replace, translate](http://pix1.agoda.net/hotelimages/300/3008492/3008492_17121510550060424840.jpg?s=800x)
In Python, you can replace strings using the replace() and translate() methods, or the regular expression functions, re.sub() and re.subn(). You can also replace substrings at specified positions using slicing.
You can also remove a substring by replacing it with an empty string ().
For extracting substrings or finding their positions, see the following articles.
There are also methods to convert between uppercase and lowercase letters.
If you want to replace the contents of a text file, read the file as a string, process it, and save it again.
Replace substrings in a string: replace() Basic usageUse the replace() method to replace substrings.
Specify the old string old for the first argument and the new string new for the second argument.
s = one two one two one print(s.replace( , -)) # one-two-one-two-oneYou can remove old by specifying new as the empty string .
print(s.replace( , )) # onetwoonetwoone Specify the max...取得本站獨家住宿推薦 15%OFF 訂房優惠
本站住宿推薦 20%OFF 訂房優惠,親子優惠,住宿折扣,限時回饋,平日促銷
Find and replace text using regular expressions | Re search and replace
Find and replace text using regular expressions | Re search and replace
How to input a regex in string.replace? | Re search and replace
How to input a regex in string.replace? | Re search and replace
Python Regex Replace Pattern in a string using re.sub() | Re search and replace
Python regex replace | Re search and replace
Python regex replace | Re search and replace
Python regex | Re search and replace
Replace strings in Python (replace, translate | Re search and replace
![](https://i.imgur.com/axBPWDg.jpg)