4

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'
Krzysztof Słowiński
  • 6,239
  • 8
  • 44
  • 62

4 Answers4

6

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.

taras
  • 6,566
  • 10
  • 39
  • 50
3

The easiest way to do this would be with split and join.

>>> (' '*n).join(s.split())

Note : The ' '*n is just for convenience in case of the need to join with many whitespaces in between.

#driver values :

IN : s = 'a  b    b'
     n = 1
OUT : 'a b b'

IN : s = '  a b   c  '
     n = 2
OUT : 'a  b  c'
Kaushik NP
  • 6,733
  • 9
  • 31
  • 60
1

Try this.

def spaces_btw_characters(word, spaces):
    return (' '*spaces).join(word.split())
  • Why? While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Nic3500 Sep 06 '18 at 10:32
  • First of all this is my first comment here as u could notice, and yeah its better to provide additional context but i felt like it wasn't necessary in this case while i just have 2 lines of code and it's obvious what those 2 lines do. But anyway thanks for the feedback. – A. Dhiblawe Sep 06 '18 at 11:05
  • Think of it like you are not only responding to the question owner, you are responding to everyone who will research the same subject later. – Nic3500 Sep 06 '18 at 11:08
0

We yourstring.strip() for string to finish spaces from start and end. You can use join() on your string to format string according to your need. Hope this helps you.

Mirza715
  • 420
  • 5
  • 15