如何从字符串中修剪空格?
- 2025-02-20 09:24:00
- admin 原创
- 77
问题描述:
如何从 Python 中的字符串中删除前导和尾随空格?
" Hello world " --> "Hello world"
" Hello world" --> "Hello world"
"Hello world " --> "Hello world"
"Hello world" --> "Hello world"
解决方案 1:
要删除字符串周围的所有空格,请使用.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
".strip(" ")
'Hello
'
最多删除一个空格:
def strip_one_space(s):
if s.endswith(" "): s = s[:-1]
if s.startswith(" "): s = s[1:]
return s
>>> strip_one_space(" Hello ")
' Hello'
解决方案 2:
正如上面的答案所指出的那样
my_string.strip()
将删除所有前导和尾随空格字符,例如`、
、
、
`、 空格。
为了更加灵活,请使用以下
仅删除前导空格字符:
my_string.lstrip()
仅删除尾随的空格字符:
my_string.rstrip()
删除特定的空白字符:`my_string.strip('
')或
my_string.lstrip('
')或
my_string.rstrip('
')`等等。
更多详细信息请参阅文档。
解决方案 3:
strip
也不限于空格字符:
# remove all leading/trailing commas, periods and hyphens
title = title.strip(',.-')
解决方案 4:
这将删除以下所有前导和尾随空格myString
:
myString.strip()
解决方案 5:
你想要strip()
:
myphrases = [" Hello ", " Hello", "Hello ", "Bob has a cat"]
for phrase in myphrases:
print(phrase.strip())
解决方案 6:
这也可以用正则表达式来实现
import re
input = " Hello "
output = re.sub(r'^s+|s+$', '', input)
# output = 'Hello'
解决方案 7:
好吧,作为一名初学者,看到这个帖子让我头晕目眩。因此我想出了一个简单的捷径。
尽管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)
在继承不同的函数时会很有帮助。
解决方案 8:
为了删除在 Pyhton 中运行完成的代码或程序时导致大量缩进错误的“空格”。只需执行以下操作;显然,如果 Python 一直提示错误是第 1、2、3、4、5 行等处的缩进...,只需来回修复该行即可。
但是,如果您仍然遇到与输入错误、运算符等相关的程序问题,请务必阅读 Python 错误向您大喊大叫的原因:
首先要检查的是缩进是否正确。如果正确,请检查代码中是否混合了制表符和空格。
请记住:代码看起来不错(对您而言),但解释器拒绝运行它。如果您怀疑这一点,一个快速解决方法是将代码放入 IDLE 编辑窗口,然后选择“编辑...”从菜单系统中选择“全部”,然后选择“格式...”取消制表符区域。如果您将制表符与空格混合使用,这将一次性将所有制表符转换为空格(并修复任何缩进问题)。
解决方案 9:
我找不到我想要的解决方案,所以我创建了一些自定义函数。你可以尝试一下。
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("
Str: {0} Len: {1} Cleansed: {2} Len: {3}".format(s1, len(s1), cdd, len(cdd)))
print("
Str: {0} Len: {1} Cleansed: {2} Len: {3}".format(s2, len(s2), cddd, len(cddd)))
print("
Str: {0} Len: {1} Cleansed: {2} Len: {3}".format(s3, len(s3), clean1, len(clean1)))
print("
Str: {0} Len: {1} Cleansed: {2} Len: {3}".format(s4, len(s4), clean2, len(clean2)))
解决方案 10:
如果您想要从左侧和右侧修剪指定数量的空格,您可以这样做:
def remove_outer_spaces(text, num_of_leading, num_of_trailing):
text = list(text)
for i in range(num_of_leading):
if text[i] == " ":
text[i] = ""
else:
break
for i in range(1, num_of_trailing+1):
if text[-i] == " ":
text[-i] = ""
else:
break
return ''.join(text)
txt1 = " MY name is "
print(remove_outer_spaces(txt1, 1, 1)) # result is: " MY name is "
print(remove_outer_spaces(txt1, 2, 3)) # result is: " MY name is "
print(remove_outer_spaces(txt1, 6, 8)) # result is: "MY name is"
解决方案 11:
如何从 Python 中的字符串中删除前导和尾随空格?
因此,下面的解决方案将删除前导和尾随空格以及中间空格。例如,如果您需要获取没有多个空格的清晰字符串值。
>>> str_1 = ' Hello World'
>>> print(' '.join(str_1.split()))
Hello World
>>>
>>>
>>> str_2 = ' Hello World'
>>> print(' '.join(str_2.split()))
Hello World
>>>
>>>
>>> str_3 = 'Hello World '
>>> print(' '.join(str_3.split()))
Hello World
>>>
>>>
>>> str_4 = 'Hello World '
>>> print(' '.join(str_4.split()))
Hello World
>>>
>>>
>>> str_5 = ' Hello World '
>>> print(' '.join(str_5.split()))
Hello World
>>>
>>>
>>> str_6 = ' Hello World '
>>> print(' '.join(str_6.split()))
Hello World
>>>
>>>
>>> str_7 = 'Hello World'
>>> print(' '.join(str_7.split()))
Hello World
如您所见,这将删除字符串中的所有多个空格(输出为Hello World
全部)。位置无关紧要。但如果您确实需要前导和尾随空格,那么strip()
就会找到。
解决方案 12:
一种方法是使用 .strip() 方法(删除所有周围的空格)
str = " Hello World "
str = str.strip()
**result: str = "Hello World"**
请注意,.strip() 返回字符串的副本并且不会改变下划线对象(因为字符串是不可变的)。
如果您希望删除所有空白(不仅仅是修剪边缘):
str = ' abcd efgh ijk '
str = str.replace(' ', '')
**result: str = 'abcdefghijk'
解决方案 13:
您还可以将其用作str.strip()
函数:
str.strip(" Hello world ") # 'Hello world'
str.lstrip()
与和相同str.rstrip()
:
str.lstrip(" hello ") # 'hello '
str.rstrip(" hello ") # ' hello'
如果你需要在可调用上下文中使用它,那么这很有用。例如,我们可以通过映射str.strip
到列表来去除列表中字符串中的空格:
lst = [" Hello ", " Hello", "Hello ", " Bob has a cat "]
list(map(str.strip, lst))
# ['Hello', 'Hello', 'Hello', 'Bob has a cat']
另一个例子:pandasstr.strip
确实很慢,但是将 Python 映射str.strip
到列上的速度要快 2 倍,特别是因为我们不需要构造 lambda 来使用它:
pd.Series(lst).map(str.strip)
解决方案 14:
我想删除字符串中过多的空格(也包括字符串之间的空格,而不仅仅是开头或结尾的空格)。我这样做是因为我不知道如何做到这一点:
string = "Name : David Account: 1234 Another thing: something "
ready = False
while ready == False:
pos = string.find(" ")
if pos != -1:
string = string.replace(" "," ")
else:
ready = True
print(string)
这将在一个空格中替换双空格,直到不再有双空格为止
扫码咨询,免费领取项目管理大礼包!