Sorting and pushing numbers from a list that contains both numbers and letters to a dictionary

Question:

I am trying to find a way to get input from the user which is a list of numbers and words. Then I want to print out only the numbers from that list. I can’t figure out how to separate them, and then only print out the numbers. I think that the answer might be through exporting the items in the list that are numbers to a dictionary and then printing said dictionary, but I don’t know how to do that. Here is the code that I have already:

string1=input("Please input a set of positive numbers and words separated by a space: ")
string2=string1.split(" ")
string3=[string2]
dicts={}
for i in string3:
    if isinstance(i, int):
        dicts[i]=string3[i]

print(dicts)
Asked By: TenseSnake9

||

Answers:

You just need to split the words into a list, then print the words in the list based on whether the characters in each word are all digits or not (using str.isdigit):

string1 = input("Please input a set of positive numbers and words separated by a space: ")
# split into words
words = string1.split(' ')
# filter words and print
for word in words:
    if word.isdigit():
        print(word)

For an input of abd 13 453 dsf a31 5b 42 ax12yz, this will print:

13
453
42

Alternatively you could filter the list of words (e.g. using a list comprehension) and print that:

numbers = [word for word in words if word.isdigit()]
print(numbers)

Output for the above sample data would be:

['13', '453', '42']
Answered By: Nick

Here is a slight variation of @Nick ‘s answer that uses list comprehension, separating the input into a list that contains only the numbers.

string1 = input("Please input a set of positive numbers and words separated by a space: ")
numbers = [x for x in string1.split(" ") if x.isdigit()]
print(numbers)
Answered By: H_Boofer
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.