简体   繁体   English

执行 strip 以删除字符串中的多余空间

[英]Perform strip to remove extra space in the string

I have a string in which the elements are seperated by a pipe operator.我有一个字符串,其中的元素由 pipe 运算符分隔。 l="EMEA | US| APAC| France & étranger| abroad ". l="欧洲、中东和非洲 | 美国 | 亚太地区 | 法国 & étranger | 国外 ". I split the list with the '|'我用“|”分割列表and the result is now in a list.结果现在在列表中。

The elements have unwanted space before and some have them after.元素之前有不需要的空间,有些元素之后有空间。 I want to modify the list such that the elements don't have unwanted space.我想修改列表,使元素没有不需要的空间。

bow= "EMEA | US| APAC| France & étranger| abroad "
attr_len = len(attr.split(' '))
bow = bow.split('|')
for i in bow:
     i.strip()

The output still shows the list having strings with unwanted space. output 仍然显示包含不需要空格的字符串的列表。

To answer the poor guy's mutilated by others now question,回答这个可怜的家伙现在被别人肢解的问题,

l= "EMEA | US| APAC| France & étranger| abroad "
l = l.split('|')
for i in l: i.strip()

You are modifying the string in-place but the original list isn't being modified by your for loop.您正在就地修改字符串,但原始列表未被您的 for 循环修改。

You are modifying the string within the for loop which is entirely different from the string in the list.您正在修改与列表中的字符串完全不同的 for 循环中的字符串。

One would write something like the following:一个人会写这样的东西:

l= "EMEA | US| APAC| France & étranger| abroad "
l = l.split('|')
for i in range(len(l)):
    l[i] = l[i].strip()

Or written in a more fancy way,或者写成更花哨的方式,

l= "EMEA | US| APAC| France & étranger| abroad "
l = l.split('|')
l = [i.strip() for i in l]

To make changes in the string itself, youu can write a function for it.要更改字符串本身,您可以为其编写一个 function。 Your use of the strip() will not save changes to the input string because as stated by others here.您对strip()的使用不会保存对输入字符串的更改,因为正如此处其他人所述。 strip() computes a new string so you have to save it somewhere. strip()计算一个新字符串,所以你必须把它保存在某个地方。

Here's my function based solution.这是我基于 function 的解决方案。 I made it generic so you can use any delimiter and not just the pipe.我将其设为通用,因此您可以使用任何定界符而不仅仅是 pipe。

def remove_space(str, delim):
   str = str.split(delim)
   for i in range(len(str)):
      str[i]=str[i].strip()
   return delim.join(str)

bow= "EMEA | US| APAC| France & étranger| abroad "
bow = remove_space(bow,"|")
print(bow)

Output: Output:

EMEA|US|APAC|France & étranger|abroad

You need use a variable to hold the i.strip() value.您需要使用一个变量来保存 i.strip() 值。 Strip method will return a string as output we need hold it. Strip 方法将返回一个字符串 output 我们需要保留它。

bow= "EMEA | US| APAC| France & étranger| abroad "

bow = bow.split('|')
for i in bow:
    k= i.strip()
    print(k)

output:
EMEA
US
APAC
France & étranger
abroad

Hope your issue is resloved.希望您的问题得到解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM