1

I have a string and I want to remove duplicate spaces from that. But my string has a new line character \n and after doing this, this character also is deleted.
Output of this:

s = 'A B     C  D \n EF   G'
print(s)
s = " ".join(s.split())
print(s)

is as follows:

A B     C  D 
 EF   G
------------
A B C D EF G

But I do not want to remove this character. The desired output:

A B C D
 EF G
Meysam
  • 409
  • 4
  • 14

4 Answers4

0

use filter.

a='A B     C  D \n EF   G'
b=" ".join(list(filter(None,a.split(" "))))
print(b)
Yash
  • 1,271
  • 1
  • 7
  • 9
0

You could use a pattern to match 2 or more whitespace chars without the newline, and in the replacement use a single space.

[^\S\r\n]{2,}

Regex demo | Python demo

For example

import re

s = 'A B     C  D \n EF   G'
print(re.sub(r"[^\S\r\n]{2,}", " ", s))

Output

A B C D 
 EF G
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
0

Try using regex.

Split the string by '\n' and then combine multiple whitespace into 1 whitespace.

import re
comb_whitespace = re.compile(r"\s+")
for i in s.split('\n'):
    print(comb_whitespace.sub(" ", i))

A B C D 
 EF G
Pygirl
  • 12,969
  • 5
  • 30
  • 43
0

It’s need to add \n split

s = 'A B     C  D \n EF   G'
print(s)
s = " ".join(s.split())
s = " ".join(s.split('\n'))
print(s)

Outs

A B     C  D 
 EF   G
A B C D EF G
Timur U
  • 415
  • 2
  • 14