简体   繁体   中英

How do I take a string of numbers in Python 2.7.2 and make each number its own element in a list?

I have a string of numbers. I would like to take each number and insert it into a list where each number is its own element in the list so I can use a For loop to search for that number. In the code below I have written an example:

string = "3, 4, 5, 99"

a_list = []

a_list.append(string)

for i in range (0, len(a_list)):
    if int(a_list[i]) == 99:
        print "yes 99 is in here"

I would like the loop to print "yes 99 is in here" because it is. I think the problem with my code is that entire string is listed as element 0 (the only element) in the list. Please help!! I know this is basic, but I'm having trouble finding the solution online. I'm new to programming.

You need to parse the string to separate each number as it's own element. Luckily Python has your back with that.

>>> a_list= string.split(", ")
>>> a_list
['3', '4', '5', '99']
l = map(int, s.split(','))
if 99 in l:
    print "yes 99 is in here"

We are splitting your list at the comma and then mapping this to an integer type. Otherwise you'd have a list filled with strings.

After the first line, your list looks like this:

[3, 4, 5, 99]

Your check then is as simple as seeing if 99 is in your list ( l )

Try

string_list = [float(i) for i in string.split(', ')]

if 99 in string_list:
    print '99 is here'

The string split method creates a list of the individual numbers but they are strings. So the [float(i) for i in string.split(', ')] part converts them all to floats. You can use int(i) if you know they will be integers or you want to interpret them as such.

remove spaces at the beginning and end (if present) using str.strip .

then split the string with ',' as delimiter using str.split which returns a list of strings.

Convert each element in list to int

string = "3, 4, 5, 99"

strings = string.strip().split(",")

a_list = [int(i) for i in strings]

for i in range (0, len(a_list)):
    if int(a_list[i]) == 99:
        print "yes 99 is in here"

Why not instead:

if string == "99" or\
   string.startswith("99,") or\
   string.endswith(", 99") or\
   ", 99," in string: print "Hooray!"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM