How to remove whitespace from a string in Python

4 Answers

0 votes
import re
 
s = '   Python   programming   '
 
s = re.sub(r"\s+$", "", s)
 
print(s)
 
  
  
'''
run:
  
Python   programming
  
'''

 



answered Apr 12, 2021 by avibootz
0 votes
s = '   Python   programming   '
 
s = s.strip()
 
print(s)
 
  
  
'''
run:
  
Python   programming
  
'''

 



answered Apr 12, 2021 by avibootz
0 votes
s = '   Python   programming   '
 
s = s.replace(" ", "")
 
print(s)
 
  
  
'''
run:
  
Pythonprogramming
  
'''

 



answered Apr 12, 2021 by avibootz
0 votes
import re

s = '   Python   programming   '

s = " ".join(re.split(r"\s+", s))
 
print(s)



'''
run:

Python programming 

'''

 



answered Apr 12, 2021 by avibootz

Related questions

1 answer 154 views
1 answer 159 views
3 answers 282 views
1 answer 203 views
1 answer 197 views
1 answer 123 views
...