im making this program wherein it takes a string as an input, and then prints the number of characters in the string where it is not one of the following: a vowel and punctuation marks. i want it to use list comprehension. i know how to exclude vowels, but i dont know how to do it for punctuations and i get an error:
UnboundLocalError Traceback (most recent call last)
<ipython-input-41-ac1f245059d7> in <module>
2 punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
3 stri = input("Enter a string: ")
----> 4 print("Count:", len([letter for letter in stri if letter not in vowels and punctuation for punctuation in stri if punctuation not in punctuations]))
<ipython-input-41-ac1f245059d7> in <listcomp>(.0)
2 punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
3 stri = input("Enter a string: ")
----> 4 print("Count:", len([letter for letter in stri if letter not in vowels and punctuation for punctuation in stri if punctuation not in punctuations]))
UnboundLocalError: local variable 'punctuation' referenced before assignment
this is my code:
`vowels = ['A', 'E', 'I', 'O', 'U', 'a','e','i','o','u']
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
stri = input("Enter a string: ")
print("Count:", len([letter for letter in stri if letter not in vowels and punctuation for punctuation in stri if punctuation not in punctuations]))`
My vowel part is correct:
`len([letter for letter in stri if letter not in vowels`
but how should i do the punctuation marks?
something like this should be the output:
Enter a string: Coding!
Count: 4
(4 because only c,d,n,g were counted because o,i,! are vowels/punctuation marks.)
CodePudding user response:
vowels = ['A', 'E', 'I', 'O', 'U', 'a','e','i','o','u']
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
stri = input("Enter a string: ")
[x for x in stri if x not in (*vowels,*punctuations)]
print(len([x for x in stri if x not in (*vowels,*punctuations)]))
CodePudding user response:
You can do multiple things;
- Make a list
not_allowed = vowels.extend(punctuations)
and then look in that
n_chars = len([letter for letter in stri if letter not in not_allowed])
- If you have to use the two lists
punctuation = list(punctuation)
n_chars = len([letter for letter in stri if (letter not in vowels and letter not in punctuation)]))`
- Use the answer from "God is One" (best idea)
CodePudding user response:
import string
vowels = list("AEIOUaeiou")
s = list(input("Enter a string: "))
print(f'count: {len([letter for letter in s if letter not in vowels and letter not in list(string.punctuation)])}')