Replace Characters
Goal¶
This post aims to introduce how to replace the characters in python.
Create strings¶
# 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
Replace characters¶
.replace('{old}', '{new}')
¶
# .replace('{old}', '{new}')
strings.replace('S', 'a')
.replace
can be chained¶
# .replace can be chained
strings.replace('(', '').replace(' ', '_')
replace multiple characters using dictionary¶
d_replace = {'(': '',
')': '',
' ': '',
',': ''}
for old, new in d_replace.items():
print(f'replace {old} with {new} ')
strings = strings.replace(old, new)
strings