简体   繁体   中英

Convert type 'str' to numerator/ denominator

I'm having some trouble converting type 'str' to numbers. I use a separate text-file containing the following numbers 1, 2, 3, 4, 5, 6 and then I import these numbers into python and save them as a list. However, by doing this, I get a list of strings as follows: ['1', '2', '3', '4', '5', '6'] . I want to convert this list of strings so the list represents numbers, ie the output should be [1, 2, 3, 4, 5, 6] .

My code is:

def imported_numbers(filename):
    with open(filename, 'r') as f: 
        contents = f.read().splitlines() 
    print(contents)
imported_numbers('sample.txt')

Is there a specific command to do this?

IMO it's more pythonic to say

str_list = ['1', '2', '3']
new_list = [int(n) for n in str_list]

If you're not sure all of the strings will be valid numbers, you need to add appropriate error handling.

You can use map :

l = ['1', '2', '3', '4', '5', '6']

new_l = list(map(int, l))  # or just map(int, l) in Python 2

will return

[1, 2, 3, 4, 5, 6]

This can throw an error if there are strings that cannot be converted to numbers though:

l = ['1', '2', '3', '4', '5', 'lkj']

list(map(int, l))

ValueError: invalid literal for int() with base 10: 'lkj'

So make sure your input is valid and/or wrap it into a try/except .

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