I have a string in which the elements are seperated by a pipe operator. l="EMEA | US| APAC| France & étranger| abroad ". 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.
CodePudding user response:
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.
You are modifying the string within the for loop which is entirely different from the string in the list.
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]
CodePudding user response:
To make changes in the string itself, youu can write a function for it. Your use of the strip()
will not save changes to the input string because as stated by others here. strip()
computes a new string so you have to save it somewhere.
Here's my function based solution. I made it generic so you can use any delimiter and not just the 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:
EMEA|US|APAC|France & étranger|abroad
CodePudding user response:
You need use a variable to hold the i.strip() value. Strip method will return a string as output we need hold it.
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.