- You can remove the trailing whitespaces with the
strip
method.
- You can remove the all spaces (or other characters) with the
replace
method.
- You can remove the all whitespaces with the
split
and join
.
- The
split
method splits a string into a list.
You can specify the separator, default separator is any whitespace.
- The
join
method takes all items in an iterable and joins them into one string.
- You can remove the all whitespaces with the
translate
and the build-in string
module
Code:
import string
input_text = """
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Cras mattis purus nec aliquam placerat.
Donec efficitur ex vel ante mattis fermentum."""
print("ORIGINAL:
{}".format(input_text))
print("
WITHOUT TRAILING WHITESPACES:
{}".format(input_text.strip()))
print("
WITHOUT SPACES:
{}".format(input_text.replace(" ", "")))
print("
WITHOUT ANY WHITESPACES:
{}".format("".join(input_text.split())))
# It works only in Python3
print(
"
WITHOUT ANY WHITESPACES:
{}".format(
input_text.translate(str.maketrans("", "", string.whitespace))
)
)
Output:
>>> python3 test.py
ORIGINAL:
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Cras mattis purus nec aliquam placerat.
Donec efficitur ex vel ante mattis fermentum.
WITHOUT TRAILING WHITESPACES:
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Cras mattis purus nec aliquam placerat.
Donec efficitur ex vel ante mattis fermentum.
WITHOUT SPACES:
Loremipsumdolorsitamet,consecteturadipiscingelit.
Crasmattispurusnecaliquamplacerat.
Donecefficiturexvelantemattisfermentum.
WITHOUT ANY WHITESPACES:
Loremipsumdolorsitamet,consecteturadipiscingelit.Crasmattispurusnecaliquamplacerat.Donecefficiturexvelantemattisfermentum.
WITHOUT ANY WHITESPACES:
Loremipsumdolorsitamet,consecteturadipiscingelit.Crasmattispurusnecaliquamplacerat.Donecefficiturexvelantemattisfermentum.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…