by @kodeazy
How to replace whitespaces in A String with underscore without using replace function in python?
- In this blog we will be discussing on how to replace all occurances 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 aString
. - 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 appendingunderscore
. -
Below is the example syntax.
string = string[:pos] + '_' + string[pos+1:]
- In the above syntax
pos
is the index at which we replaceempty space with
_`. - Below is an example code on how to replace all occurances of
whitespace
withunderscore
.
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