DEV Community

kode eazy
kode eazy

Posted on β€’ Originally published at kodeazy.com

1 1

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

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

πŸ‘‹ Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay