Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Substitute multiple whitespace with single whitespace in Python [duplicate]

I have this string:

mystring = 'Here is  some   text   I      wrote   ' 

How can I substitute the double, triple (...) whitespace chracters with a single space, so that I get:

mystring = 'Here is some text I wrote' 
like image 520
creativz Avatar asked Jan 16 '10 15:01

creativz


People also ask

How do I replace multiple spaces with a single space in Python?

Use the re. sub() method to replace multiple spaces with a single space, e.g. result = re. sub(' +', ' ', my_str) .

How do I replace multiple spaces in single space?

The metacharacter “\s” matches spaces and + indicates the occurrence of the spaces one or more times, therefore, the regular expression \S+ matches all the space characters (single or multiple). Therefore, to replace multiple spaces with a single space.

How do I remove double spacing from a string in Python?

Using regexes with "\s" and doing simple string. split()'s will also remove other whitespace - like newlines, carriage returns, tabs.


1 Answers

A simple possibility (if you'd rather avoid REs) is

' '.join(mystring.split()) 

The split and join perform the task you're explicitly asking about -- plus, they also do the extra one that you don't talk about but is seen in your example, removing trailing spaces;-).

like image 78
Alex Martelli Avatar answered Sep 21 '22 18:09

Alex Martelli