0

I have a list filled with string objects. If the string object ends in a W, I want to delete/remove the W from the string. Also, in the only case that the string equals UW I do not want to remove the W.

I have tried this:

masterAbrevs = []

for subject in masterAbrevs:
    if subject.endswith("W"):
        subject =  subject[:-1]

After printing masterAbrevs it appears that my code is doing absolutely nothing. kindly help.

Community
  • 1
  • 1
Philip McQuitty
  • 1,077
  • 9
  • 25
  • 36

4 Answers4

6

The problem is that you're never making the change to the element in the list; you're making the change to the variable holding the element returned from the list.

Try this instead:

masterAbrevs = ['ASW', 'AS', 'UW']

for i, e in enumerate(masterAbrevs):
    if (e[-1] == 'W') and (e != 'UW'):
        masterAbrevs[i] = masterAbrevs[i][:-1]

# results in ['AS', 'AS', 'UW']
sgarza62
  • 5,998
  • 8
  • 49
  • 69
1

You need to make use of enumerate() here.

masterAbrevs = ['aksdjfW', 'adW', 'UW', 'tttttW']

for ind, subject in enumerate(masterAbrevs):
    if subject.endswith("W") and subject[-2] != 'U':
        masterAbrevs[ind] = subject[:-1]

print masterAbrevs
# ['aksdjf', 'ad', 'UW', 'ttttt']
Weafs.py
  • 22,731
  • 9
  • 56
  • 78
1

Thought you might appreciate a more pythonic answer:

masterAbrevs = ['aksdjfW', 'adW', 'UW', 'tttttW']
masterAbrevs = [abrev[:-1] if (abrev.endswith("W") and abrev != "UW") else abrev for abrev in masterAbrevs]
Sean Johnson
  • 5,567
  • 2
  • 17
  • 22
  • 1
    Though not an issue for small lists, it should be noted that using a list comprehension creates a completely new list. – sgarza62 Jan 04 '15 at 05:28
  • 1
    I don't think you could call any line over 80 characters 'pythonic' ;) – sapi Jan 04 '15 at 05:34
  • If the list is not small, a lazy iterable would seem more appropriate. Plus, extracting the conditional into its own function would make the whole thing more readable. – kojiro Jan 04 '15 at 05:35
1

You might consider a different approach using a generator or map expression to encapsulate the operation on the inner string:

def rstrip_most_ws(s):
    '''Remove trailing 'W' if s is not 'UW'
    '''
    if s != 'UW' and s[-1] == 'W':
        return s[:-1]
    return s

masterAbrevs = (rstrip_most_ws(s) for s in masterAbrevs)

It might seem more efficient to manually change the strings in-place, but Python has optimizations for generator and list expressions, so this approach might not be much slower.

kojiro
  • 74,557
  • 19
  • 143
  • 201