I was wondering how I would get my code to detect double digits or triple digits and put them into the list. Currently it separates any double digits and assigns a list value for each digit instead of each number. For example if the user enters "5 55 6 45 3", the programs enters it as ["5","5","5","6","4","5","3"].Thank you.
main_list = list(input("Enter numbers: "))
for vals in main_list:
if vals == " ":
main_list.remove(vals)
print("The original numbers are",main_list)
You can use the .split()
method for strings (working with the string directly, not list(...)
): input("Enter numbers: ").split(' ')
returns
["5", "55", "6", "45", "3"]
i.e. it splits the string at each ' '
. Be careful of what happens if there is a double space: You will get empty strings in the list. So the best way to go is probably to check if the string is non-empty:
[x for x in input("Enter numbers: ").split(' ') if x]
Note also that this works in Python3.x only (because the return value of input
is a string). The corresponding function for Python 2 is raw_input()
. So if you need to make it compatible with both you could use
try:
[x for x in raw_input("Enter numbers: ").split(' ') if x]
except NameError:
[x for x in input("Enter numbers: ").split(' ') if x]
but not the other way around (input()
exists in Python2, it just does't do the same thing).