This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 4 years ago.
I am trying to make a program where it takes in user input and spits out the input without the letters. I'm really confused on why this isn't working.
numText = input("Give me a list of characters: ") # Gets user input of characters
numList = list(numText) # Turns ^ into list
for char in numList: # Every character in the list
if char.isalpha(): # Checks to see if the character is a letter
numList.remove(char) # Removes the letter from the list
print(numList) # Prints the new list without letters
input("") # Used so the program doesnt shut off
I know this is really dumb so im sorry for asking.
You should not iterate and remove at the same time, instead use a list comprehension.
numText = input("Give me a list of characters: ") # Gets user input of characters
numList = [char for char in numText if not char.isalpha()]
print(numList) # Prints the new list without letters
input("")
Related
This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 7 months ago.
import string
CHARACTERS = list(string.ascii_letters) + [" "]
def letter_frequency(sentence):
frequencies = [(c, 0) for c in CHARACTERS]
for letter in sentence:
index = CHARACTERS.index(letter)
frequencies[index] = (letter, frequencies[index][1] + 1)
for item in frequencies:
if item[1] == 0:
frequencies.remove(item)
return frequencies
This is based on an exercise in the book Object Oriented Programming. It's just a means of counting letters in a sentence and presenting them as a list of tuples with letters and their corresponding counts.
I wanted to remove the letters in the resulting list of the alphabet that have '0' count, but when I execute the code, it only removes every 2nd item in the list. What am I doing wrong?
There is another short way to calculate the number of times a letter occurred inside a sentence:
from collections import Counter
counter = Counter('Put your sentence here')
print(counter)
This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 2 years ago.
I have a list of words, and a function that searches for a word by its length and the letters inside the word.
The for loop at the end cycles through the list of possible words (generated by the given length), and it should either print the word if it contains the given letter, or delete the word from the list of possible words if it does not contain the given letter.
How can I achieve this here:
wlist = ['Apple', 'Banana', 'Cherry', 'Donkey']
def wordSearch(wlist):
posWords = []
length = int(input('Enter length of word: '))
print("POSSIBLE WORD(S):")
for word in wlist:
stripWord = word.replace(' ', '')
if len(stripWord) == length:
print("%s (%s)" % (word, length))
posWords.append(word)
while True:
searchOptions = ['Add Known Letter', 'Exit']
searchIndex, item = chooseFromMenu(searchOptions)
if searchIndex == 0:
letter = input('Enter letter: ')
print("POSSIBLE WORD(S):")
for word in posWords:
if letter in word:
print(word)
else:
# remove word from list somehow
else:
break
Specifically this block:
letter = input('Enter letter: ')
print("POSSIBLE WORD(S):")
for word in posWords:
if letter in word:
print(word)
else:
# remove word from list somehow
I've tried to do del word and posWords.pop(word) but neither seem to work.
I also tried .remove() but I cant exactly remember what I did with that.
I'll go into more detail with the problem I'm having here...
If I type in the letter 'e', it should remove 'Banana' from the list of possible words so that when I type 'n' I should only get 'Donkey', not 'Donkey' and 'Banana'.
If that makes sense.
I have just tried posWords.remove(word) and it hasn't done this either...
You can iterate over the list in reverse, so that removing an element doesn't affect the rest of the iteration.
for i in range(len(posWords)-1, -1, -1):
if letter in posWords[i]:
print(posWords[i])
else:
posWords.pop(i)
This is the solution in this answer to the question you said didn't solve your problem.
Note that the argument to pop() is the list index, not a list element.
You can use a while loop and only increase the iterator, if no item is removed.
i = 0
while i < len(posWords):
if letter in word:
print(word)
i += 1
else:
del posWords[i] # posWords.pop(i) does the same
This works, because if an item is removed, the next items index is reduced by 1 so i now points to the next item
If I'm understanding your question properly then the following should work:
letter = input('Enter letter: ')
print("POSSIBLE WORD(S):")
for word in posWords[:]:
if letter in word:
print(word)
else:
posWords.remove(word)
This question already has answers here:
Why doesn't calling a string method (such as .replace or .strip) modify (mutate) the string?
(3 answers)
What is the difference between Python's list methods append and extend?
(20 answers)
Closed 3 months ago.
I am trying to create a list with user input that has at least eight items in the list. I can make the list and put in the user input, but I need to validate that there are indeed eight items, and ask for more if there are not. Then I need the list to print.
I have tried using a while statement for len(list)<8, and an if/else statement for the same. Both are asking for the additional input, but neither are printing the list at the end. I tried a nested loop with while len(list)<8 and inside is an if/else loop, but that returned the same errors as the original while statement.
>>>def main():
... userinput= input("Enter a list of at least eight words separated by a comma: ")
... list= userinput.split(",")
... while len(list)<7:
... print("Please enter more words")
... more_input= input()
... more_input.split(",")
... list.append(more_input)
... print(list)
OR
>>> def main():
... userinput= input("Enter a list of at least eight words separated by a comma: ")
... list= userinput.split(",")
... if len(list)<7:
... print("Please enter more words")
... more_input= input()
... more_input.split(",")
... list.append(more_input)
... else:
... print(list)
Errors with while loop: It just keeps asking for more input even when the list has the minimum required input
>>> main()
Enter a list of at least eight words separated by a comma: This, is, a, list
Please enter more words
More, words
Please enter more words
Three, more, words
Please enter more words
Errors with if/else loop: It only checks once. If the length is good, it prints the list. If the length is not good, it asks for more input and then stops. It neither checks the length again nor prints the list.
Your code seems ok but the problem is that you are splitting the input coming from user but this split input does not have a variable. I mean, you are still adding the non split input to the list. I edited the code which you can see below.
def main():
userinput= input("Enter a list of at least eight words separated by a comma: ")
input_list = userinput.split(",")
while len(input_list)<7:
print("Please enter more words")
more_input= input()
splitted_more_input = more_input.split(",") # problem fixed here
for i in splitted_more_input: # split creates another list
input_list.append(i) # add inputs individual
print(input_list)
Try this if you want to merge the split sub-lists in the main list :
def main():
list_= []
print("Enter a list of at least eight words separated by a comma: ")
while len(list_)<7:
print("Please enter more words")
userinput = input()
temp = userinput.split(",")
list_ += temp
print(list_)
main()
Output :
Enter a list of at least eight words separated by a comma:
Please enter more words
This, is, a, list
Please enter more words
more, words
Please enter more words
three, more, words
['This', ' is', ' a', ' list', 'more', ' words', 'three', ' more', ' words']
Note : Avoid assigning variable name as list as it's builtin keyword in python.
Since you need to repeatedly execute a function till a certain condition is met, you could take the help of recursive functions as follows
def main():
userinput= input("Enter a list of at least eight words separated by a comma: ")
words = userinput.split(",")
if len(words) == 8:
print (words)
else:
A = reenter_words(words)
print (A)
def reenter_words(words):
if len(words) == 8:
return words
else:
IN = input("More words are needed:")
new_words = words + IN.split(",")
return reenter_words(new_words)
Here I am recursively calling the reenter_words function till we get eight words from the user.
SAMPLE OUTPUT
Enter a list of at least eight words separated by a comma: qq,ww,ee,rr,tt
More words are needed:gg,hh
More words are needed:kk
['qq', 'ww', 'ee', 'rr', 'tt', 'gg', 'hh', 'kk']
This question already has answers here:
How to check if a string contains a string from a list?
(5 answers)
Check presence of vowels in a string
(6 answers)
Closed 5 years ago.
I'm writing a program that is supposed to take an input and output what the most common vowel is as seen here:
while True:
string = input("Enter a line of text: ")
vowel = "aeiouAEIOU"
x = Counter(c for c in string.upper() if c in vowel)
most = {k: x[k] for k in x if x[k] == max(x.values())}
for i in most:
vowel = i
y = most [i]
print("The most frequently occurring vowel in the string is: " ,vowel, "with ,y, "occurrences.")
break
But I can't figure out how to have an error message if there are no vowels in the input. I have tried:
if vowel != string:
print("Error, no vowels were detected in the user input.")
continue
But this doesn't work. If I put it before the section where it outputs the most common vowel, then no matter what is input the error message shows and the input starts again. If I put it after that, then the vowels are detected and most common is printed, but it continues to display the error message and restart the input instead of breaking the program.
How can I write the error so that it looks at the input to see if there are any vowels in there and displays the error if there aren't any?
Since you already have a counter of all vowels (x) it would be a waste to check (again) whether user input contains vowels. You could simply check that x is empty (i.e., that it has not counted any vowels):
if not x:
print("Error, no vowels were detected in the user input.")
continue
In addition, consider either dropping .upper() from c for c in string.upper() if c in vowel OR dropping lower case letters from vowel = "aeiouAEIOU". Keeping both is unnecessary.
This question already has answers here:
Extract elements of list at odd positions
(5 answers)
Closed 7 years ago.
I have to do this for school, but I can't work it out. I have to get an input and print ONLY the odd characters. So far I've put the input in a list and I have a while loop (which was a clue on the task sheet), but I can't work it out. Please help:
inp = input('What is your name? ')
name = []
name.append(inp)
n=1
while n<len(name):
print inp[1::2]
I guess thats all you need
You don't need to put the string in a list, a string is already essentially a list of characters (more formally, it is a "sequence").
You can use indexing and the modulus operator (%) for this
inp = input('What is your name? ')
n = 0 # index variable
while n < len(inp):
if n % 2 == 1: # check if it is an odd letter
print(inp[n]) # print out that letter
n += 1