python整数转换字符串
Given a string with digits and we have to convert the string to its equivalent list of the integers in Python.
给定一个带有数字的字符串,我们必须将该字符串转换为Python中与之等效的整数列表。
Example:
例:
Input:
str1 = "12345"
Output:
int_list = [1, 2, 3, 4, 5]
Input:
str1 = "12345ABCD"
Output:
ValueError
Note: The string must contain only digits between 0 to 9, if there is any character except digits, the program will through a ValueError.
注意:该字符串只能包含0到9之间的数字,如果除数字之外还有任何其他字符,则程序将通过ValueError进行操作 。
如何将字符(仅数字)转换为整数? (How to convert character (only digit) to integer?)
To convert a character (that is digit only like: ‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’) to integer, we use int() function – which is a library function in Python. int() returns integer value equivalent to given character i.e. digit in character form.
转换字符(仅是数字,例如: “ 0”,“ 1”,“ 2”,“ 3”,“ 4”,“ 5”,“ 6”,“ 7”,“ 8”,“ 9” )转换为整数,我们使用int()函数-这是Python中的库函数。 int()返回等于给定字符的整数值,即字符形式的数字。
print (int('0'))
print (int('1'))
print (int('2'))
print (int('3'))
print (int('4'))
print (int('5'))
print (int('6'))
print (int('7'))
print (int('8'))
print (int('9'))
Output
输出量
0
1
2
3
4
5
6
7
8
9
Python程序将字符串转换为整数列表 (Python program to convert a string to integers list)
Here, we have a string “12345” and we are converting it to integers list [1, 2, 3, 4, 5].
在这里,我们有一个字符串“ 12345” ,并将其转换为整数列表[1、2、3、4、5] 。
# program to convert string to integer list
# language: python3
# declare a list
str1 = "12345"
# list variable to integeres
int_list =[]
# converting characters to integers
for ch in str1:
int_list.append(int(ch))
# printing the str_list and int_list
print ("str1: ", str1)
print ("int_list: ", int_list)
Output
输出量
str1: 12345
int_list: [1, 2, 3, 4, 5]
ValueError (ValueError)
If there is any character except the digits, there will be an error “ValueError: invalid literal for int() with base 10”.
如果除数字外没有其他字符,将出现错误“ ValueError:int()的基数为10的无效文字” 。
Program with Error:
出现错误的程序:
# program to convert string to integer list
# language: python3
# declare a list
str1 = "12345ABCD"
# list variable to integeres
int_list =[]
# converting characters to integers
for ch in str1:
int_list.append(int(ch))
# printing the str_list and int_list
print ("str1: ", str1)
print ("int_list: ", int_list)
Output
输出量
Traceback (most recent call last):
File "/home/main.py", line 12, in
int_list.append(int(ch))
ValueError: invalid literal for int() with base 10: 'A'
翻译自: https://www.includehelp.com/python/convert-a-string-to-integers-list.aspx
python整数转换字符串