如何在Python中删除字符串开头和结尾的空格?
" Hello world " --> "Hello world"
" Hello world" --> "Hello world"
"Hello world " --> "Hello world"
"Hello world" --> "Hello world"
要删除字符串周围的所有空白字符,请使用.strip()
。例如:
>>> ' Hello '.strip()
'Hello'
>>> ' Hello'.strip()
'Hello'
>>> 'Bob has a cat'.strip()
'Bob has a cat'
>>> ' Hello '.strip() # ALL consecutive spaces at both ends removed
'Hello'
注意,str.strip()
方法会移除所有空白字符,包括制表符和换行符。如果你只想移除空格,请在strip
方法中指定要移除的特定字符作为参数:>>> " Hello\n ".strip(" ")
'Hello\n'
要删除最多只有一个空格:
def strip_one_space(s):
if s.endswith(" "): s = s[:-1]
if s.startswith(" "): s = s[1:]
return s
>>> strip_one_space(" Hello ")
' Hello'
rstrip()
函数。 :-) - Nikhil Girrajstrip
而不是 trim
,isinstance
而不是 instanceof
,list
而不是 array
等等。为什么不使用所有人都熟悉的名称呢?真是的 :P - Gershom Maesstrip
的情况下,我完全同意,但是列表与数组完全不同。 - Jacqlyn如上面的答案所指出的
my_string.strip()
这个函数会移除所有的前导和尾随空白字符, 例如 \n
, \r
, \t
, \f
, 空格
.
如果需要更多的灵活性,可以使用以下函数:
my_string.lstrip()
my_string.rstrip()
my_string.strip('\n')
或 my_string.lstrip('\n\r')
或 my_string.rstrip('\n\t')
等等。更多细节请参阅 文档。
strip
不仅限于空格字符:
# remove all leading/trailing commas, periods and hyphens
title = title.strip(',.-')
以下代码可以移除 myString
字符串中所有的前导和尾随空白:
myString.strip()
你需要使用 strip()
函数:
myphrases = [" Hello ", " Hello", "Hello ", "Bob has a cat"]
for phrase in myphrases:
print(phrase.strip())
这也可以用正则表达式来实现
import re
input = " Hello "
output = re.sub(r'^\s+|\s+$', '', input)
# output = 'Hello'
作为初学者,看到这个帖子让我头晕目眩。因此,我想出了一个简单的快捷方式。
虽然 str.strip() 可以去除开头和结尾的空格,但它对字符之间的空格无能为力。
words=input("Enter the word to test")
# If I have a user enter discontinous threads it becomes a problem
# input = " he llo, ho w are y ou "
n=words.strip()
print(n)
# output "he llo, ho w are y ou" - only leading & trailing spaces are removed
所以使用 str.replace() 更合理,更少出错且更直观。以下代码可概括 str.replace() 的使用。
def whitespace(words):
r=words.replace(' ','') # removes all whitespace
n=r.replace(',','|') # other uses of replace
return n
def run():
words=input("Enter the word to test") # take user input
m=whitespace(words) #encase the def in run() to imporve usability on various functions
o=m.count('f') # for testing
return m,o
print(run())
output- ('hello|howareyou', 0)
在不同的函数中继承相同内容时可能会有帮助。
str = " Hello World "
str = str.strip()
**result: str = "Hello World"**
str = ' abcd efgh ijk '
str = str.replace(' ', '')
**result: str = 'abcdefghijk'
我找不到我需要的解决方案,所以我创建了一些自定义函数。你可以试试它们。
def cleansed(s: str):
""":param s: String to be cleansed"""
assert s is not (None or "")
# return trimmed(s.replace('"', '').replace("'", ""))
return trimmed(s)
def trimmed(s: str):
""":param s: String to be cleansed"""
assert s is not (None or "")
ss = trim_start_and_end(s).replace(' ', ' ')
while ' ' in ss:
ss = ss.replace(' ', ' ')
return ss
def trim_start_and_end(s: str):
""":param s: String to be cleansed"""
assert s is not (None or "")
return trim_start(trim_end(s))
def trim_start(s: str):
""":param s: String to be cleansed"""
assert s is not (None or "")
chars = []
for c in s:
if c is not ' ' or len(chars) > 0:
chars.append(c)
return "".join(chars).lower()
def trim_end(s: str):
""":param s: String to be cleansed"""
assert s is not (None or "")
chars = []
for c in reversed(s):
if c is not ' ' or len(chars) > 0:
chars.append(c)
return "".join(reversed(chars)).lower()
s1 = ' b Beer '
s2 = 'Beer b '
s3 = ' Beer b '
s4 = ' bread butter Beer b '
cdd = trim_start(s1)
cddd = trim_end(s2)
clean1 = cleansed(s3)
clean2 = cleansed(s4)
print("\nStr: {0} Len: {1} Cleansed: {2} Len: {3}".format(s1, len(s1), cdd, len(cdd)))
print("\nStr: {0} Len: {1} Cleansed: {2} Len: {3}".format(s2, len(s2), cddd, len(cddd)))
print("\nStr: {0} Len: {1} Cleansed: {2} Len: {3}".format(s3, len(s3), clean1, len(clean1)))
print("\nStr: {0} Len: {1} Cleansed: {2} Len: {3}".format(s4, len(s4), clean2, len(clean2)))
rstrip
的陷阱。'WKHS.US.TXT'.rstrip('.US.TXT')
将返回WKH
而不是WKHS
。这个rstrip
会产生一个难以排查的 BUG。 - huang.split('.')[0]
即可 - Coder