Convert string number to integer python

Convert string number to integer python

Здесь Python понимает, что вы хотите сохранить целое число 110 в виде строки или используете целочисленный тип данных:

Важно учитывать, что конкретно подразумевается под «110» и 110 в приведённых выше примерах. Для человека, который использовал десятичную систему счисления всю жизнь очевидно, что речь идёт о числе сто десять. Однако другие системы счисления, такие, как двоичная и шестнадцатеричная, используют иные основания для представления целого числа.

Например, вы представляете число сто десять в двоичном и шестнадцатеричном виде как 1101110 и 6e соответственно.

А также записываете целые числа в других системах счисления в Python с помощью типов данных str и int:

>>> binary = 0b1010 >>> hexadecimal = "0xa" 

Обратите внимание, что binary и hexadecimal используют префиксы для идентификации системы счисления. Все целочисленные префиксы имеют вид 0? , где ? заменяется символом, который относится к системе счисления:

  1. b: двоичная (основание 2);
  2. o: восьмеричная (основание 8);
  3. d: десятичная (основание 10);
  4. 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() :

  1. Синтаксическая ошибка ValueError возникает, когда int() не знает, как интерпретировать строку с использованием предоставленного основания (10 по умолчанию).
  2. Логическая ошибка 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() не способен интерпретировать двоичную строку как десятичное целое число.

Читайте также:  Python execute command exit code

Когда передаёте строку 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.

  1. Как использовать str и int для хранения целых чисел.
  2. Как указать явную систему счисления для целочисленного представления.
  3. Как преобразовать строку Python в int .
  4. Как преобразовать Python int в строку.

Теперь, когда вы усвоили материал о str и int , читайте больше о представлении числовых типов с использованием float(), hex(), oct() и bin()!

Источник

How to Convert a Python String to int

Python Pit Stop

Integers are whole numbers. In other words, they have no fractional component. Two data types you can use to store an integer in Python are int and str . These types offer flexibility for working with integers in different circumstances. In this tutorial, you’ll learn how you can convert a Python string to an int . You’ll also learn how to convert an int to a string.

By the end of this tutorial, you’ll understand:

  • How to store integers using str and int
  • How to convert a Python string to an int
  • How to convert a Python int to a string

Python Pit Stop: This tutorial is a quick and practical way to find the info you need, so you’ll be back to your project in no time!

Free Bonus: Click here to get a Python Cheat Sheet and learn the basics of Python 3, like working with data types, dictionaries, lists, and Python functions.

Representing Integers in Python

An integer can be stored using different types. Two possible Python data types for representing an integer are:

For example, you can represent an integer using a string literal:

Here, Python understands you to mean that you want to store the integer 110 as a string. You can do the same with the integer data type:

It’s important to consider what you specifically mean by «110» and 110 in the examples above. As a human who has used the decimal number system for your whole life, it may be obvious that you mean the number one hundred and ten. However, there are several other number systems, such as binary and hexadecimal, which use different bases to represent an integer.

Читайте также:  Python tkinter text wrap

For example, you can represent the number one hundred and ten in binary and hexadecimal as 1101110 and 6e respectively.

You can also represent your integers with other number systems in Python using the str and int data types:

>>> binary = 0b1010 >>> hexadecimal = "0xa" 

Notice that binary and hexadecimal use prefixes to identify the number system. All integer prefixes are in the form 0? , in which you replace ? with a character that refers to the number system:

Technical Detail: The prefix is not required in either an integer or string representation when it can be inferred.

int assumes the literal integer to be decimal:

>>> decimal = 303 >>> hexadecimal_with_prefix = 0x12F >>> hexadecimal_no_prefix = 12F File "", line 1 hexadecimal_no_prefix = 12F ^ SyntaxError: invalid syntax 

The string representation of an integer is more flexible because a string holds arbitrary text data:

>>> decimal = "303" >>> hexadecimal_with_prefix = "0x12F" >>> hexadecimal_no_prefix = "12F" 

Each of these strings represent the same integer.

Now that you have some foundational knowledge about how to represent integers using str and int , you’ll learn how to convert a Python string to an int .

Converting a Python String to an int

If you have a decimal integer represented as a string and you want to convert the Python string to an int , then you just pass the string to int() , which returns a decimal integer:

By default, int() assumes that the string argument represents a decimal integer. If, however, you pass a hexadecimal string to int() , then you’ll see a ValueError :

>>> int("0x12F") Traceback (most recent call last): File "", line 1, in ValueError: invalid literal for int() with base 10: '0x12F' 

The error message says that the string is not a valid decimal integer.

It’s important to recognize the difference between two types of failed results of passing a string to int() :

  1. Syntax Error: A ValueError will occur when int() doesn’t know how to parse the string using the provided base (10 by default).
  2. Logical Error: int() does know how to parse the string, but not the way you expected.

Here’s an example of a logical error:

>>> binary = "11010010" >>> int(binary) # Using the default base of 10, instead of 2 11010010 

In this example, you meant for the result to be 210, which is the decimal representation of the binary string. Unfortunately, because you didn’t specify that behavior, int() assumed that the string was a decimal integer.

One good safeguard for this behavior is to always define your string representations using explicit bases:

>>> int("0b11010010") Traceback (most recent call last): File "", line 1, in ValueError: invalid literal for int() with base 10: '0b11010010' 

Here, you get a ValueError because int() doesn’t know how to parse the binary string as a decimal integer.

When you pass a string to int() , you can specify the number system that you’re using to represent the integer. The way to specify the number system is to use base :

Now, int() understands you are passing a hexadecimal string and expecting a decimal integer.

Technical Detail: The argument that you pass to base is not limited to 2, 8, 10, and 16:

Great! Now that you’re comfortable with the ins and outs of converting a Python string to an int , you’ll learn how to do the inverse operation.

Converting a Python int to a String

In Python, you can convert a Python int to a string using str() :

By default, str() behaves like int() in that it results in a decimal representation:

In this example, str() is smart enough to interpret the binary literal and convert it to a decimal string.

If you want a string to represent an integer in another number system, then you use a formatted string, such as an f-string (in Python 3.6+), and an option that specifies the base:

>>> octal = 0o1073 >>> f"octal>" # Decimal '571' >>> f"octal:x>" # Hexadecimal '23b' >>> f"octal:b>" # Binary '1000111011' 

str is a flexible way to represent an integer in a variety of different number systems.

Conclusion

Congratulations! You’ve learned so much about integers and how to represent and convert them between Python string and int data types.

In this tutorial, you learned:

  • How to use str and int to store integers
  • How to specify an explicit number system for an integer representation
  • How to convert a Python string to an int
  • How to convert a Python int to a string

Now that you know so much about str and int , you can learn more about representing numerical types using float() , hex() , oct() , and bin() !

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Convert a Python String to int

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

About Alex Ronquillo

Alex Ronquillo is a Software Engineer at thelab. He’s an avid Pythonista who is also passionate about writing and game development.

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Aldren Santos

Jon Fincher

Master Real-World Python Skills With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Master Real-World Python Skills
With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal. Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session. Happy Pythoning!

Related Tutorial Categories: basics python

Источник

Оцените статью