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]:
'String (structure), a long flexible structure made from threads twisted together, which is used to tie, bind, or hang other objects'

Replace characters

.replace('{old}', '{new}')

In [16]:
# .replace('{old}', '{new}')
strings.replace('S', 'a')
Out[16]:
'atringstructurealongflexiblestructuremadefromthreadstwistedtogetherwhichisusedtotiebindorhangotherobjects'

.replace can be chained

In [5]:
# .replace can be chained
strings.replace('(', '').replace(' ', '_')
Out[5]:
'String_structure),_a_long_flexible_structure_made_from_threads_twisted_together,_which_is_used_to_tie,_bind,_or_hang_other_objects'

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
replace ( with  
replace ) with  
replace   with  
replace , with  
Out[15]:
'Stringstructurealongflexiblestructuremadefromthreadstwistedtogetherwhichisusedtotiebindorhangotherobjects'

Comments

Comments powered by Disqus