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!!
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.
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.
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.
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!!
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.
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.
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.