change white space with regular expression in python

Question:

I need to change white space to a character, but only if there are two or more white spaces and there is only one I want to keep it.

An example of text is:
142526 0x8520003 2 2022-10-20 The interface status changes. (ifName=Gig.

I need:
142526;0x8520003;2;2022-10-20 The interface status changes. (ifName=Gig.

I use:

';'.join(headers.split())

but change one space white also. Thanks!!

Asked By: crist_9

||

Answers:

Use re.split() to match more than one space.

import re

new_headers = ';'.join(re.split(r's{2,}', headers))

s matches whitespace, and {2,} means to match 2 or more of them in a row.

Answered By: Barmar

You can try to use maxsplit= parameter in str.split:

s = """142526     0x8520003  2     2022-10-20 The interface status changes. (ifName=Gig."""

s = ";".join(s.split(maxsplit=3))
print(s)

Prints:

142526;0x8520003;2;2022-10-20 The interface status changes. (ifName=Gig.
Answered By: Andrej Kesely

Could be done using re.sub, see this demo at tio.run.

headers = re.sub(r"[ t]{2,}", ";", headers)

The pattern will match two or more horizontal spaces.

Answered By: bobble bubble
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.