1

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.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Samuel
  • 29
  • 3
  • 3
    `i.strip()` computes a **new** string and **does not change** the string object that was in the list. Even re-assigning a different string to `i` would not affect the list, because that is just rebinding the name - Python does not use "references". Instead, use a different technique to produce a new list of the modified results, as shown in the first linked duplicate. – Karl Knechtel Jan 12 '23 at 05:24
  • 2
    My duplicate links certainly were correct. OP was asking about what was wrong with the iterative code. I linked the canonical explanations of the points made in my comment, which cover the problem with the approach. – Karl Knechtel Jan 12 '23 at 05:27
  • 2
    Does this answer your question? [Why doesn't .strip() remove whitespaces?](https://stackoverflow.com/questions/40444787/why-doesnt-strip-remove-whitespaces) – Pranav Hosangadi Jan 12 '23 at 05:30
  • 1
    @SulemanElahi, obtaining `"France&étranger"` (rather than `"France & étranger"`) is not what OP desired. – J_H Jan 12 '23 at 06:21

2 Answers2

-1

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]
-2

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.

  • This answer doesn't answer the question and is just a copy of what the author already tried to do. Take a look at the comments on the original post to see why this doesn't solve the problem. – Simon S. Jan 12 '23 at 15:25
  • This is my own code, no need to copy from another author. – Gopi Reddy Feb 01 '23 at 05:31