- Как преобразовать строку в int в Python – 3 способа
- Вывод
- Как преобразовать String в Int и Int в String в Python?
- 1. Преобразование строки Python в int
- ValueError Exception при преобразовании строки Python в int
- Преобразование списка целых чисел в список строк
- 2. Преобразование Python int в String
- Python String to Int, Int to String
- Python String to Int
- Converting String to int from different base
- ValueError when converting String to int
- Python int to String
Как преобразовать строку в int в Python – 3 способа
В этом руководстве мы изучим способы преобразования строки в целое число в Python.
Давайте посмотрим на пример, прежде чем продолжить:
a='Learning Python is fun' b= 20 #Displaying the type of a and b print(type(a)) print(type(b))
В приведенном выше примере мы объявили переменные ‘a’ и ‘b’ со строковым и целочисленным значением соответственно.
Мы можем проверить их типы данных с помощью type().
Здесь возникает вопрос, зачем нам преобразовывать строку в целое число.
Следующая программа иллюстрирует то же самое:
value_a = "100" value_b = "26" res = value_a * value_b print("The multiplication of val_a and val_b gives: ",res)
res = value_a * value_b TypeError: can't multiply sequence by non-int of type 'str'
Поскольку сгенерировалась ошибка, это причина того, что мы должны преобразовать строковые значения в целые числа, чтобы мы могли продолжить операцию.
Пришло время взглянуть на первую программу, демонстрирующую преобразование строки в целое число.
a = '7' print(type(a)) #using int() conv_a=int(a) print(type(conv_a)) conv_a = conv_a+10 print(conv_a) print(type(conv_a))
- Первый шаг – объявить переменную a со строковым значением.
- После этого мы проверили ее тип данных с помощью type().
- Для преобразования строки в целое число мы использовали int(), а затем проверили ее тип.
- Теперь мы поработали с переменной «а», добавив к ней 10.
- Наконец, на выходе отображается результирующее значение.
В следующем примере мы применим косвенный подход к преобразованию строки в целое число.
Следующая программа показывает, как это можно сделать:
value_a = "100" value_b = "26" print(type(value_a)) print(type(value_b)) #converting to float value_a=float(value_a) #converting to int value_b=int(value_b) res_sum=value_a+value_b print("The sum of value_a and value_b is ",res_sum)
The sum of value_a and value_b is 126.0
- Первый шаг – объявить две переменные value_a и value_b со строковым значением.
- После этого проверили их тип данных с помощью type().
- Для преобразования строки в целое число мы использовали float() для преобразования строки в значение с плавающей запятой.
- На следующем шаге преобразуем строковое значение value_b в целое число.
- Теперь мы сложили value_a и value_b и распечатали их сумму.
- Наконец, на выходе отображается результирующее значение.
Здесь мы увидим, как мы можем преобразовать число, представленное в виде строкового значения, в основание 10, когда оно находится на разных основаниях.
num_value = '234' # printing the value of num_value print('The value of num_value is :', num_value) #converting 234 to base 10 assuming it is in base 10 print('The value of num_value from base 10 to base 10 is:', int(num_value)) #converting 234 to base 10 assuming it is in base 8 print('The value of num_value from base 8 to base 10 is :', int(num_value, base=8)) #converting 234 to base 10 assuming it is in base 6 print('The value of num_value base 6 to base 10 is :', int(num_value, base=6))
The value of num_value is: 234 The value of num_value from base 10 to base 10 is: 234 The value of num_value from base 8 to base 10 is: 156 The value of num_value base 6 to base 10 is: 94
- На первом этапе мы объявили значение переменной.
- Поскольку вывод всегда будет в базе 10, мы предоставили различные базовые значения внутри int().
- В качестве базовых значений мы взяли 10, 8 и 6.
- При выполнении программы отображается ожидаемый результат.
Вывод
В этом руководстве мы узнали о различных способах преобразования строки в значение типа int.
Как преобразовать String в Int и Int в String в Python?
В этой статье мы разберемся с преобразованием Python String в Int и int в преобразование строки. В Python значения никогда не приводятся к типу неявно. Давайте узнаем, как явно приводить типы переменных.
1. Преобразование строки Python в int
Метод Python int() позволяет преобразовать любое значение типа String в целочисленное значение.
string_num = '75846' print("The data type of the input variable is:\n") print(type(string_num)) result = int(string_num) print("The data type of the input value after conversion:\n") print(type(result)) print("The converted variable from string to int:\n") print(result)
The data type of the input variable is: The data type of the input value after conversion: The converted variable from string to int: 75846
Python также предоставляет нам эффективный вариант преобразования чисел и значений типа String в целочисленные значения с определенной базой в соответствии с системой счисления.
int(string_value, base = val)
string_num = '100' print("The data type of the input variable is:\n") print(type(string_num)) print("Considering the input string number of base 8. ") result = int(string_num, base = 8) print("The data type of the input value after conversion:\n") print(type(result)) print("The converted variable from string(base 8) to int:\n") print(result) print("Considering the input string number of base 16. ") result = int(string_num, base = 16) print("The data type of the input value after conversion:\n") print(type(result)) print("The converted variable from string(base 16) to int:\n") print(result)
В приведенном выше фрагменте кода мы преобразовали «100» в целочисленное значение с основанием 8 и основанием 16 соответственно.
The data type of the input variable is: Considering the input string number of base 8. The data type of the input value after conversion: The converted variable from string(base 8) to int: 64 Considering the input string number of base 16. The data type of the input value after conversion: The converted variable from string(base 16) to int: 256
ValueError Exception при преобразовании строки Python в int
Сценарий: Если какая-либо из входных строк содержит цифру, не принадлежащую к десятичной системе счисления.
В приведенном ниже примере, если вы хотите преобразовать строку «A» в целочисленное значение A с основанием 16, и мы не передаем base = 16 в качестве аргумента методу int(), тогда это вызовет исключение ValueError.
Поскольку, хотя ‘A’ является шестнадцатеричным значением, оно не принадлежит к десятичной системе счисления, оно не будет рассматривать A как эквивалент десятичного числа 10, пока мы не передадим base = 16 в качестве аргумента в функцию int().
string_num = 'A' print("The data type of the input variable is:\n") print(type(string_num)) result = int(string_num) print(type(result)) print("The converted variable from string(base 16) to int:\n") print(result)
The data type of the input variable is: Traceback (most recent call last): File "main.py", line 4, in result = int(string_num) ValueError: invalid literal for int() with base 10: 'A'
Преобразование списка целых чисел в список строк
Список Python, содержащий целочисленные элементы, может быть преобразован в список значений String с помощью метода int() вместе со списком понимания.
st_lst = ['121', '144', '111', '564'] res_lst = [int(x) for x in st_lst] print (res_lst)
2. Преобразование Python int в String
Метод Python str() позволяет преобразовать любое значение целочисленного типа в значение String.
int_num = 100 print("The data type of the input variable is:\n") print(type(int_num)) result = str(int_num) print("The data type of the input value after conversion:\n") print(type(result)) print("The converted variable from int to string:\n") print(result)
The data type of the input variable is: The data type of the input value after conversion: The converted variable from int to string: 100
Python String to Int, Int to String
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
In this tutorial, we will learn how to convert python String to int and int to String in python. In our previous tutorial we learned about Python List append function.
Python String to Int
If you read our previous tutorials, you may notice that at some time we used this conversion. Actually, this is necessary in many cases. For example, you are reading some data from a file, then it will be in String format and you will have to convert String to an int. Now, we will go straight to the code. If you want to convert a number that is represented in the string to int, you have to use int() function to do so. See the following example:
num = '123' # string data # print the type print('Type of num is :', type(num)) # convert using int() num = int(num) # print the type again print('Now, type of num is :', type(num))
Type of num is : Now, type of num is :
Converting String to int from different base
If the string you want to convert into int belongs to different number base other that base 10, you can specify the base for conversion. But remember that the output integer is always in base 10. Another thing you need to remember is that the given base must be in between 2 to 36. See the following example to understand the conversion of string to int with the base argument.
num = '123' # print the original string print('The original string :', num) # considering '123' be in base 10, convert it to base 10 print('Base 10 to base 10:', int(num)) # considering '123' be in base 8, convert it to base 10 print('Base 8 to base 10 :', int(num, base=8)) # considering '123' be in base 6, convert it to base 10 print('Base 6 to base 10 :', int(num, base=6))
The output of the following code will be
ValueError when converting String to int
While converting from string to int you may get ValueError exception. This exception occurs if the string you want to convert does not represent any numbers. Suppose, you want to convert a hexadecimal number to an integer. But you did not pass argument base=16 in the int() function. It will raise a ValueError exception if there is any digit that does not belong to the decimal number system. The following example will illustrate this exception while converting a string to int.
""" Scenario 1: The interpreter will not raise any exception but you get wrong data """ num = '12' # this is a hexadecimal value # the variable is considered as decimal value during conversion print('The value is :', int(num)) # the variable is considered as hexadecimal value during conversion print('Actual value is :', int(num, base=16)) """ Scenario 2: The interpreter will raise ValueError exception """ num = '1e' # this is a hexadecimal value # the variable is considered as hexadecimal value during conversion print('Actual value of \'1e\' is :', int(num, base=16)) # the variable is considered as decimal value during conversion print('The value is :', int(num)) # this will raise exception
The value is : 12 Actual value is : 18 Actual value of '1e' is : 30 Traceback (most recent call last): File "/home/imtiaz/Desktop/str2int_exception.py", line 22, in print('The value is :', int(num)) # this will raise exception ValueError: invalid literal for int() with base 10: '1e'
Python int to String
Converting an int to string requires no effort or checking. You just use str() function to do the conversion. See the following example.
hexadecimalValue = 0x1eff print('Type of hexadecimalValue :', type(hexadecimalValue)) hexadecimalValue = str(hexadecimalValue) print('Type of hexadecimalValue now :', type(hexadecimalValue))
Type of hexadecimalValue : Type of hexadecimalValue now :
That’s all about Python convert String to int and int to string conversion. Reference: Python Official Doc
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us