In this blog we will discuss on how to replace all occurrences of whitespaces with underscore in a string in python .
I have a string as below.
string = 'Lets start coding in python'
To replace the particular character like empty space of all occurrences in a String
loop through the characters of the string and check for the empty space.
If found empty space at particular index replace the character by dividing into substrings and appending underscore
Below is the example syntax
string = string[:pos] + '_' + string[pos+1:]
In the above syntax pos is the index at which we replace empty space with _.
Below is the example code.
string = 'Lets start coding in python'
for pos in range(0, len(string)):
if(string[pos]==' '):
string = string[:pos] + '_' + string[pos+1:]
print(string)
Output
Lets_start_coding_in_python
Related Blogs
https://kodeazy.com/python-replace-character-in-string/
Originally Published at
https://kodeazy.com/
Follow us https://twitter.com/bugsanalyze
Top comments (0)