This is my first post on dev.to, and i decided talk to about Python, my main programming language, and create a series named 'Python Utility Belt' which basically will be composed of small strategies to solve common problems in a development day.
In this post we will talk to about chars replacement.
So, lets imagine a simple example... you have the following string:
music = "Stairway_to_heaven-Led_Zeppelin.mp3"
And you need to replace "_" with spaces, in Python it is easy, you just need run:
and you will receive:
Stairway to heaven-Led Zeppelin.mp3
Its so easy, isn't it?! But, what if you desire to replace
. with spaces ???
A python beginner can imagine a code like this:
music.replace('_',' ').replace('-',' ').replace('.',' ')
yeah... And it is a common answer in stackoverflow. Does the code above works? yep, it works, but there is another way to solve the same problem: using re lib. You just need to import
re in you code and use the
import re music = "Stairway_to_heaven-Led_Zeppelin.mp3" print(re.sub('_|-|\.', ' ', music))
In this example, we called the sub function that receives three parameters:
re.sub(char that will be replaced,new char,string)
to replace multiple chars using the first parameter we used
regex, but we will not delve into it, no. Basically each char that need to be replaced is separated by
|, so if you need to replace just
- you can run
re.sub('_|-', ' ', music). Note that
. is accompanied by
\, it is because in Regex,
. has a another functionality, so we need to use
\ to specify the use of a dot.
I will finalize this post here.
Please, comment if you found any error on post (English, programming, syntax).
This helps me to improve.