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

How to convert string into number in python

步履不停
Release: 2019-07-23 13:35:07
Original
30035 people have browsed it

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']
Copy after login

Want to convert each element into a number:

numbers = [1, 5, 10, 8]
Copy after login

Use a loop to solve:

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

Is there a simpler statement that can be done?

1.

numbers = [ int(x) for x in numbers ]
Copy after login

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

numbers = map(int, numbers)
Copy after login

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

numbers = list(map(int, numbers))
Copy after login

3. There is another more complicated point:

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

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template