Replace Characters
Goal¶
This post aims to introduce how to replace the characters in python.
Create strings¶
In [2]:
# Create strings
strings = 'String (structure), a long flexible structure made from threads twisted together, which is used to tie, bind, or hang other objects'
strings
Out[2]:
Replace characters¶
.replace('{old}', '{new}')
¶
In [16]:
# .replace('{old}', '{new}')
strings.replace('S', 'a')
Out[16]:
.replace
can be chained¶
In [5]:
# .replace can be chained
strings.replace('(', '').replace(' ', '_')
Out[5]:
replace multiple characters using dictionary¶
In [15]:
d_replace = {'(': '',
')': '',
' ': '',
',': ''}
for old, new in d_replace.items():
print(f'replace {old} with {new} ')
strings = strings.replace(old, new)
strings
Out[15]:
Comments
Comments powered by Disqus