python整数转换字符串_Python | 将字符串转换为整数列表
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:ValueErrorNote: 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 9Python程序將字符串轉換為整數列表 (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整數轉換字符串
總結
以上是生活随笔為你收集整理的python整数转换字符串_Python | 将字符串转换为整数列表的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java enummap_Java En
- 下一篇: java dataset redis,利