- Python cast str to int
- Преобразование строки Python в int
- Преобразование Python int в строку
- Заключение
- Python Convert String to Int – How to Cast a String in Python
- Data types in Python
- Data type conversion
- How to convert a string to an integer in Python
- A practical example of converting a string to an int
- Conclusion
Python cast str to int
Здесь Python понимает, что вы хотите сохранить целое число 110 в виде строки или используете целочисленный тип данных:
Важно учитывать, что конкретно подразумевается под «110» и 110 в приведённых выше примерах. Для человека, который использовал десятичную систему счисления всю жизнь очевидно, что речь идёт о числе сто десять. Однако другие системы счисления, такие, как двоичная и шестнадцатеричная, используют иные основания для представления целого числа.
Например, вы представляете число сто десять в двоичном и шестнадцатеричном виде как 1101110 и 6e соответственно.
А также записываете целые числа в других системах счисления в Python с помощью типов данных str и int:
>>> binary = 0b1010 >>> hexadecimal = "0xa"
Обратите внимание, что binary и hexadecimal используют префиксы для идентификации системы счисления. Все целочисленные префиксы имеют вид 0? , где ? заменяется символом, который относится к системе счисления:
- b: двоичная (основание 2);
- o: восьмеричная (основание 8);
- d: десятичная (основание 10);
- x: шестнадцатеричная (основание 16).
Техническая подробность: префикс не требуется ни в int , ни в строковом представлении, когда он определён логически.
int предполагает, что целочисленный литерал – десятичный:
>>> decimal = 303 >>> hexadecimal_with_prefix = 0x12F >>> hexadecimal_no_prefix = 12F File "", line 1 hexadecimal_no_prefix = 12F ^ SyntaxError: invalid syntax
У строкового представления целого числа больше гибкости, потому что строка содержит произвольные текстовые данные:
>>> decimal = "303" >>> hexadecimal_with_prefix = "0x12F" >>> hexadecimal_no_prefix = "12F"
Каждая из этих строк представляет одно и то же целое число.
Теперь, когда мы разобрались с базовым представлением целых чисел с помощью str и int , вы узнаете, как преобразовать Python строку в int .
Преобразование строки Python в int
Если вы записали десятичное целое число в виде строки и хотите преобразовать строку Python в int , то передайте строку в метод int() , который возвращает десятичное целое число:
По умолчанию int() предполагает, что строковый аргумент представляет собой десятичное целое число. Однако если вы передадите шестнадцатеричную строку в int() , то увидите ValueError :
>>> int("0x12F") Traceback (most recent call last): File "", line 1, in ValueError: invalid literal for int() with base 10: '0x12F'
Сообщение об ошибке говорит, что строка – недопустимое десятичное целое число.
Важно понимать разницу между двумя типами неудачных результатов при передаче строки в int() :
- Синтаксическая ошибка ValueError возникает, когда int() не знает, как интерпретировать строку с использованием предоставленного основания (10 по умолчанию).
- Логическая ошибка int() интерпретирует строку, но не так, как то ожидалось.
Вот пример логической ошибки:
>>> binary = "11010010" >>> int(binary) # Using the default base of 10, instead of 2 11010010
В этом примере вы подразумевали, что результатом будет 210 – десятичное представление двоичной строки. К сожалению, поскольку точное поведение не было указано, int() предположил, что строка – десятичное целое число.
Гарантия нужного поведения – постоянно определять строковые представления с использованием явных оснований:
>>> int("0b11010010") Traceback (most recent call last): File "", line 1, in ValueError: invalid literal for int() with base 10: '0b11010010'
Здесь получаете ValueError , потому что int() не способен интерпретировать двоичную строку как десятичное целое число.
Когда передаёте строку int() , указывайте систему счисления, которую используете для представления целого числа. Чтобы задать систему счисления применяется base :
Теперь int() понимает, что вы передаёте шестнадцатеричную строку и ожидаете десятичное целое число.
Техническая подробность: аргумент base не ограничивается 2, 8, 10 и 16:
Отлично! Теперь, когда тонкости преобразования строки Python в int освоены, вы научитесь выполнять обратную операцию.
Преобразование Python int в строку
Для преобразования int в строку Python разработчик использует str() :
По умолчанию str() ведёт себя, как int() : приводит результат к десятичному представлению:
В этом примере str() блеснул «умом»: интерпретировал двоичный литерал и преобразовал его в десятичную строку.
Если вы хотите, чтобы строка представляла целое число в другой системе счисления, то используйте форматированную строку (f-строку в Python 3.6+) и параметр, который задаёт основание:
>>> octal = 0o1073 >>> f"" # Decimal '571' >>> f"" # Hexadecimal '23b' >>> f"" # Binary '1000111011'
str – гибкий способ представления целого числа в различных системах счисления.
Заключение
Поздравляем! Вы достаточно много узнали о целых числах и о том, как представлять и преобразовывать их с помощью типов данных Python.
- Как использовать str и int для хранения целых чисел.
- Как указать явную систему счисления для целочисленного представления.
- Как преобразовать строку Python в int .
- Как преобразовать Python int в строку.
Теперь, когда вы усвоили материал о str и int , читайте больше о представлении числовых типов с использованием float(), hex(), oct() и bin()!
Python Convert String to Int – How to Cast a String in Python
Dionysia Lemonaki
When you’re programming, you’ll often need to switch between data types.
The ability to convert one data type to another gives you great flexibility when working with information.
There are different built-in ways to convert, or cast, types in the Python programming language.
In this article, you’ll learn how to convert a string to an integer.
Data types in Python
Python supports a variety of data types.
Data types are used for specifying, representing, and categorizing the different kinds of data that exist and are used in computer programs.
Also, different operations are available with different types of data – one operation available in one data type is often not available in another.
One example of a data type is strings.
Strings are sequences of characters that are used for conveying textual information.
They are enclosed in single or double quotation marks, like so:
fave_phrase = "Hello world!" #Hello world! is a string,enclosed in double quotation marks
Ints, or integers, are whole numbers.
They are used to represent numerical data, and you can do any mathematical operation (such as addition, subtraction, multiplication, and division) when working with integers.
Integers are not enclosed in single or double quotation marks.
fave_number = 7 #7 is an int #"7" would not be an int but a string, despite it being a number. #This is because of the quotation marks surrounding it
Data type conversion
Sometimes when you’re storing data, or when you receive input from a user in one type, you’ll need to manipulate and perform different kinds of operations on that data.
Since each data type can be manipulated in different ways, this often means that you’ll need to convert it.
Converting one data type to another is also called type casting or type conversion. Many languages offer built-in cast operators to do just that – to explicitly convert one type to another.
How to convert a string to an integer in Python
To convert, or cast, a string to an integer in Python, you use the int() built-in function.
The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed.
The general syntax looks something like this: int(«str») .
Let’s take the following example, where there is the string version of a number:
#string version of the number 7 print("7") #check the data type with type() method print(type("7")) #output #7 #
To convert the string version of the number to the integer equivalent, you use the int() function, like so:
#convert string to int data type print(int("7")) #check the data type with type() method print(type(int("7"))) #output #7 #
A practical example of converting a string to an int
Say you want to calculate the age of a user. You do this by receiving input from them. That input will always be in string format.
So, even if they type in a number, that number will be of .
If you want to then perform mathematical operations on that input, such as subtracting that input from another number, you will get an error because you can’t carry out mathematical operations on strings.
Check out the example below to see this in action:
current_year = 2021 #ask user to input their year of birth user_birth_year_input = input("What year were you born? ") #subtract the year the user filled in from the current year user_age = current_year - user_birth_year_input print(user_age) #output #What year were you born? 1993 #Traceback (most recent call last): # File "demo.py", line 9, in # user_age = current_year - user_birth_year_input #TypeError: unsupported operand type(s) for -: 'int' and 'str'
The error mentions that subtraction can’t be performed between an int and a string.
You can check the data type of the input by using the type() method:
current_year = 2021 #ask user to input their year of birth user_birth_year_input = input("What year were you born? ") print(type(user_birth_year_input)) #output #What year were you born? 1993 #
The way around this and to avoid errors is to convert the user input to an integer and store it inside a new variable:
current_year = 2021 #ask user to input their year of birth user_birth_year_input = input("What year were you born? ") #convert the raw user input to an int using the int() function and store in new variable user_birth_year = int(user_birth_year_input) #subtract the converted user input from the current year user_age = current_year - user_birth_year print(user_age) #output #What year were you born? 1993 #28
Conclusion
And there you have it — you now know how to convert strings to integers in Python!
If you want to learn more about the Python programming language, freeCodeCamp has a Python Certification to get you started.
You’ll start with the fundamentals and progress to more advance topics like data structures and relational databases. In the end, you’ll build five projects to practice what you learned.
Thanks for reading and happy coding!