-1

Let's say I have a list that is something like this:

lst = ['Joe C', 'Jill', 'Chad', 'Cassie C']

I want to remove the last character from each string if that character is a 'C'. At the moment I'm stuck at this impass:

no_c_list = [i[:-1] for i in lst if i[-1:] == 'C']

However, this would return a list of:

['Joe', 'Cassie']
AMC
  • 2,642
  • 7
  • 13
  • 35
AfredTX
  • 5
  • 1
  • Do you plan on leaving the space between the 'C' and name? – Mark Apr 11 '20 at 00:07
  • 1
    Does this answer your question? [if else in a list comprehension](https://stackoverflow.com/questions/4406389/if-else-in-a-list-comprehension) – AMC Apr 11 '20 at 00:17

3 Answers3

2

Use rstrip:

lst = ['Joe C', 'Jill', 'Chad', 'Cassie C']

result = [e.rstrip('C') for e in lst]

print(result)

Output

['Joe ', 'Jill', 'Chad', 'Cassie ']

From the documentation:

Return a copy of the string with trailing characters removed. The chars argument is a string specifying the set of characters to be removed.

Also, as mentioned by @dawg:

result = [e.rstrip(' C') for e in lst]

If you want to remove the trailing whitespace also.

Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
1

Try this:

lst = ['Joe C', 'Jill', 'Chad', 'Cassie C']

new_list = [ i[:-2] if i[-2:] == " C" else i for i in lst ]
print(new_list)
AmirHmZ
  • 516
  • 3
  • 22
0

You could use a regex:

>>> lst = ['Joe C', 'Jill', 'Chad', 'Cassie C']
>>> import re
>>> [re.sub(r' C$', '', s) for s in lst]
['Joe', 'Jill', 'Chad', 'Cassie']
dawg
  • 98,345
  • 23
  • 131
  • 206