DEV Community

kode eazy
kode eazy

Posted on • Originally published at kodeazy.com

How to replace whitespaces in A String with underscore without using replace function in python?

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:]
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output

Lets_start_coding_in_python
Enter fullscreen mode Exit fullscreen mode

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)