Home >Backend Development >Python Tutorial >How to convert string into number in python

How to convert string into number in python

步履不停
步履不停Original
2019-07-03 13:20:4030032browse

How to convert string into number in python

The example in this article describes how to convert list elements into numbers in Python. Share it with everyone for your reference, the details are as follows:

There is a list of numeric characters:

numbers = ['1', '5', '10', '8']

Want to convert each element into a number:

numbers = [1, 5, 10, 8]

Use a loop to solve:

new_numbers = [];
for n in numbers:
  new_numbers.append(int(n));
numbers = new_numbers;

Is there a simpler statement that can be done?

1.

numbers = [ int(x) for x in numbers ]

2. Python2.x, you can use the map function

numbers = map(int, numbers)

If it is 3.x, Map returns a map object, which of course can also be converted to List:

numbers = list(map(int, numbers))

3. There is another more complicated point:

for i, v in enumerate(numbers): numbers[i] = int(v)

Recommended related tutorials: Python video tutorial

The above is the detailed content of How to convert string into number in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn