+ 2

How to Remove extra space from a string?

" My name is Python? " 1. string have not any space in beginning. 2. Have only one space between each word. 3. String end without space. => "My name is Python?"

16th Sep 2020, 3:16 AM
CHAYAN SARKAR
CHAYAN SARKAR - avatar
3 Answers
+ 14
Is this question specific to Python? In Python, there is a str.strip() method which allows you to remove leading and trailing whitespaces from a string. That solves #1 and #3. https://docs.python.org/3/library/stdtypes.html#str.strip As for #2, you can tokenize the string into a list of words using whitespaces as separator, and then rejoin the list into a stingle string, removing duplicate whitespaces. Something like " ".join("This has many spaces".split())
16th Sep 2020, 3:23 AM
Hatsy Rei
Hatsy Rei - avatar
+ 9
You can do it in more than one way you can use split of regular expressions like this import re print(re.sub(' +',' ', 'my name is Python? ')) print(' '.join('my name is python? '.split()))
16th Sep 2020, 3:25 AM
Ruba Kh
Ruba Kh - avatar