1

I'm trying to remove periods, commas, single and double quotes from the end of each string. Each string is part of a list of strings

string_list= ["cars." , "red" , "orange," , "man'" , "thus:"]

desired_output --->["cars" , "red" , "orange" , "man", "thus"]

I tried using a list comprehension, but I keep getting a list of booleans rather than the desired output:

desired_output = [sub[:-1] =='' for sub in string_list[-1] if sub[:-1]== '.' or ',' or '"' or "'" or ':' or ';' ]

not the output I want, but it outputs as :

[True, True, True, True, True]

But I think this is due to a broader point that I don't understand the ways to format the syntax, ie, which way of formatting a list comprehension will output a list of booleans, which will output the desired effect. It would be very much appreciated if a generic scheme for the types of syntax for list comprehension could be included in an answer given.

  • 2
    If that's not the output you want, why is the value of your list comprehension a *comparison*? – jonrsharpe Dec 28 '19 at 18:18
  • 2
    Why did you decide to compare anything to `''` in the first place? (Also, separate problem, [`or` doesn't work like that](https://stackoverflow.com/questions/20002503/why-does-a-b-or-c-or-d-always-evaluate-to-true).) – user2357112 Dec 28 '19 at 18:19

3 Answers3

6

You can get the desired output by using the str.rstrip built-in function and the str.punctuation string of ASCII characters:

from string import punctuation

lst = ["cars.", "red", "orange,", "man'", "thus:"]
output = [x.rstrip(punctuation) for x in lst]
Riccardo Bucco
  • 13,980
  • 4
  • 22
  • 50
2

sub[:-1] == '' is a boolean expression. It evaluates to True if the equality is true and false otherwise.

I'd use rstrip()

chars = [",", etc]

output = [item.rstrip(chars) for item in list]
Alec
  • 8,529
  • 8
  • 37
  • 63
1

you don't need to iterate over last element string_list[-1] because you just check last element, not the whole list. Also you try to filter items, not just check element to see if you need to remove punctuation or not

You can use this:

desired_output = [item[:-1]  if item[-1]  in ( '.', ',', '"', "'", ':', ';') else item for item in string_list]
Denis Yakovlev
  • 487
  • 3
  • 12