-1

I'm trying to delete leading comas in a sentence and I can't get why does this doesn't work

text = ",greetings   friends"

text_l = text.split()
for word in text_l:
    if word.startswith(','):
        word = word[1:]
text = ' '.join(text_l)

>>> ,greetings friends

but this does.

text = ",greetings   friends"

text_l = text.split()
for word in text_l:
    if word.startswith(','):
        indw = text_l.index(word)
        text_l[indw] = word[1:]
text = ' '.join(text_l)

>>> greetings friends
debrises
  • 95
  • 7
  • 1
    Possible duplicate of [Python list doesn't reflect variable change](https://stackoverflow.com/questions/12080552/python-list-doesnt-reflect-variable-change) – Georgy Jun 29 '19 at 08:51
  • 1
    indeed, you do not need to split the string. Simply do this : `if text.startswith[',']: text = text[1:]` – Masoud Jun 29 '19 at 09:00

3 Answers3

1

Your first code does not work because that only assigns a new value to the local variable word, without: changing the string in the list. Your second code works (as you noticed) but is inefficient, as you have to find the index of each word you want to strip. Instead, you can use enumerate to iterate words and indices at the same time, and also use lstrip instead of slicing the string.

text_l = text.split()
for i, word in enumerate(text_l):
    if word.startswith(','):
        text_l[i] = word.lstrip(",")
text = ' '.join(text_l)

Also, when using lstrip the if is not really necessary anymore, and we can compress the whole thing to a one-line generator expression within ' '.join(...):

text = ' '.join(word.lstrip(",") for word in text.split())
tobias_k
  • 81,265
  • 12
  • 120
  • 179
1

Variables in Python do not work as pointer, see this SO question for a better explanation. In your first bit of code you are changing the value of the variable word, not the object that word refers to, therefore your loop is not changing anything in the original list of words.

The second codes does change the original list.

As a suggestion, a more pythonic way to do what you need:

original_text = ",greetings   friends"

text = ' '.join(part.lstrip(',') for part in original_text.split())
text = ' '.join(map(lambda part: part.lstrip(','), original_text.split()))  # If you want a colleague to ask you "what's that???" :)
Hrabal
  • 2,403
  • 2
  • 20
  • 30
0

If you would like to delete a leading comma then lstrip is your desired command.

text = ",greetings   friends"

text_l = text.split()
text = []
for word in text_l:
    if word.startswith(','):
        word = word.lstrip(',')
    text.append(word)
text = ' '.join(text)

Output of text is:

greetings friends
Bryce Wayne
  • 351
  • 5
  • 17