Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format a string to have n spaces only between words in python

I am working with strings that have different number of spaces between the non-whitespace characters. The problem is that this strings form a category, and they have to be equal. I would like to format them to have exactly the same number of spaces between the non-whitespace characters, f.e. 1, but this could be generalised to insert more spaces if possible. And there should be no spaces at the beginning and end.

Examples with n=1:

'a  b    b' => 'a b c'
'  a b   c  ' => 'a b c'
like image 539
Krzysztof Słowiński Avatar asked Oct 24 '25 16:10

Krzysztof Słowiński


1 Answers

Simply split it and join the resulting list by space(es)

>>> " ".join('a  b    b'.split())
'a b c'
>>> "  ".join('  a b   c  '.split())
'a  b  c'

From str.split(sep) docs:

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.

like image 80
taras Avatar answered Oct 26 '25 06:10

taras



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!