Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
448 views
in Technique[技术] by (71.8m points)

python - 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, i.e. 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...