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

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay