Friday, 24 September 2021

Python: Remove multiple spaces in a string

Using ‘split’ and ‘join’ methods, we can remove multiple spaces in a string.

 

Step 1: Split the string by a space character.

splits = input_str.split()

 

Step 2: Join the splitted strings using space character.

' '.join(splits)

 

remove_multiple_spaces.py

def remove_multiple_spaces(input_str):
    splits = input_str.split()
    return ' '.join(splits)

input_str = '  Hello    World   How  are  you  '
result_str = remove_multiple_spaces(input_str)

print('input_str "', input_str, '"')
print('result_str "', result_str, '"')

 

Output

input_str "   Hello    World   How  are  you   "
result_str " Hello World How are you "

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment