How do I remove leading and trailing whitespace from a string in Python?
" Hello world " --> "Hello world" " Hello world" --> "Hello world" "Hello world " --> "Hello world" "Hello world" --> "Hello world"
在 Python 中,您可以使用该strip()方法从字符串中删除前导和尾随空格。以下是示例:
strip()
s = " Hello world " trimmed = s.strip() print(trimmed) # Output: "Hello world"
lstrip()
rstrip()
s1 = " Hello world " print(s1.strip()) # "Hello world" s2 = " Hello world" print(s2.strip()) # "Hello world" s3 = "Hello world " print(s3.strip()) # "Hello world" s4 = "Hello world" print(s4.strip()) # "Hello world"
该strip()方法默认适用于删除空格、制表符和换行符。