- How To Convert Integers to Strings in Python 3
- Как преобразовать целое число в строку в Python [Python Convert Int To String]
- Преобразование целого числа в строку в Python
- 1. Использование функции str()
- 2. Использование f-строк (форматированные строковые литералы)
- 3. Использование метода format()
- 4. Использование %-форматирования
- Заключение
- 4 Ways to Convert Int to String in Python
- What is Integer in Python?
- What are Strings in Python?
- Convert Int to String in Python
- 1) Using str() function
- 2) Using string formatting
- 3) Using format() method
- 4) Using F-strings
- Conclusion
- 4 Ways to Convert an Integer to a String in Python
- Convert a Python Number to String
- 1. Use of str Function
How To Convert Integers to Strings in Python 3
We can convert numbers to strings using the str() method. We’ll pass either a number or a variable into the parentheses of the method and then that numeric value will be converted into a string value.
To convert the integer 12 to a string value, you can pass 12 into the str() method:
The quotes around the number 12 signify that the number is no longer an integer but is now a string value.
With variables we can begin to see how practical it can be to convert integers to strings. Let’s say we want to keep track of a user’s daily programming progress and are inputting how many lines of code they write at a time. We would like to show this feedback to the user and will be printing out string and integer values at the same time:
user = "Sammy" lines = 50 print("Congratulations, " + user + "! You just wrote " + lines + " lines of code.")
When we run this code, we receive the following error:
OutputTypeError: Can't convert 'int' object to str implicitly
We’re not able to concatenate strings and integers in Python, so we’ll have to convert the variable lines to be a string value:
user = "Sammy" lines = 50 print("Congratulations, " + user + "! You just wrote " + str(lines) + " lines of code.")
Now, when we run the code, we receive the following output that congratulates our user on their progress:
OutputCongratulations, Sammy! You just wrote 50 lines of code.
If you want to learn more about converting Python data types, check out our How To Convert Data Types in Python 3 tutorial. You can also find more Python topics in our How To Code in Python 3 series.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Как преобразовать целое число в строку в Python [Python Convert Int To String]
В этом руководстве по Python мы обсудим, как преобразовать целое число в строку в Python. Преобразование целых чисел в строки — распространенная задача программирования, и Python предоставляет несколько встроенных функций и методов для достижения этой цели.
Чтобы преобразовать целое число в строку в Python, вы можете использовать различные методы, подобные приведенным ниже:
- Использование функции ул()
- Использование f-строк (форматированные строковые литералы)
- Использование метода формат()
- Использование %-форматирования (форматирование строки в стиле printf)
Преобразование целого числа в строку в Python
Теперь давайте проверим различные методы преобразования целого числа в строку в Python на различных примерах.
1. Использование функции str()
Функция str() — это встроенная функция Python, которая преобразует свой аргумент в строковое представление.
number = 42 string_number = str(number) print(string_number) print(type(string_number))
2. Использование f-строк (форматированные строковые литералы)
F-строки, также известные как форматированные строковые литералы, появились в Python 3.6. Они позволяют встраивать выражения в строковые литералы с помощью фигурных скобок <>.
number = 42 string_number = f"" print(string_number) print(type(string_number))
3. Использование метода format()
Метод format() — это еще один способ форматирования строк в Python. Он позволяет заменять заполнители, определенные фигурными скобками <>, значениями переменных, переданных в качестве аргументов.
number = 42 string_number = "<>".format(number) print(string_number) print(type(string_number))
4. Использование %-форматирования
Форматирование % — это более старый метод форматирования строк, вдохновленный стилем printf в C. Он использует оператор %, за которым следует спецификатор формата для определения преобразования между типами данных.
number = 42 string_number = "%d" % number print(string_number) print(type(string_number))
Заключение
В этом уроке мы изучили четыре различных метода преобразовать целое число в строку в Python:
- Использование функции ул()
- Использование f-строк
- Использование метода формат()
- Использование %-форматирования
Все эти методы действительны и могут использоваться взаимозаменяемо, в зависимости от ваших предпочтений и версии Python, с которой вы работаете. F-строки и функция str() являются наиболее современными и рекомендуемыми способами преобразования целых чисел в строки в Python.
Вам также может понравиться:
Python — один из самых популярных языков в Соединенных Штатах Америки. Я давно работаю с Python и имею опыт работы с различными библиотеками на Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn и т. д. У меня есть опыт работы с различными клиентами в таких странах, как США, Канада, Великобритания, Австралия, Новая Зеландия и т. д. Проверьте мой профиль.
4 Ways to Convert Int to String in Python
While programming in python, many operations require typecasting of data and variables from one data type to another. These conversions are sometimes made by interpreters internally while running the program. But often interpreter also fails to perform the type conversion of data type, so the programmer has to perform explicit type conversion using some default methods. Today, let us understand the conversion of Int to String in python using 4 different methods in detail, along with the example and output. But before that, take a look at a brief introduction to integer and strings in python for better understanding.
What is Integer in Python?
Int or integer in python is a whole number, either positive or negative, but without decimal points. Integers have lengths up to the memory limit of a computer, and therefore, you may never run out of integers that you can use while programming in python. By default, int is decimal, i.e., base 10, but you can also define them or use them with different bases. All integer literals or variables are the objects of the “int” class. You can use the “type()” method to identify the class name of the variable in python.
For Example
What are Strings in Python?
In python, the string is a sequence of characters wrapped around single or double quotes. You can use triple quotes to create a multi-line string in python. It is immutable in nature, which means the strings, once defined, cannot be changed again. As python does not support character data type, a single character is considered a string of length 1. There are many string manipulation methods available to perform different operations on a string. For example, join, concatenation, append, trim, etc.
These methods are not directly applied to the original string because of their immutable nature. Therefore, a copy of the original string is created, and operations are performed on it. You can use square brackets to access the element of the string using their index number.
For Example
a = 'favtutor' print(type(a)) print(a)
Convert Int to String in Python
There are total four methods by which you can convert the integer data type into string in python. Let us study all these methods in detail below:
1) Using str() function
str() is a built-in function in python programming used to convert the integer into a string. Apart from integer conversion, the str() function can take any python data type as a parameter and convert it into the string format. Take a look at the example below for a better understanding.
For Example
a = 10 print(type(a)) # converting int into string convert_a = str(a) print(type(convert_a))
2) Using string formatting
String formatting is one of the methods to insert a variable or another string into a predefined string. But apart from this, you can also use string formatting to convert an integer to a string. The “%s” keyword is used to convert int into a string. The empty string is created, and the “%s” operator is placed in it. Later, the integer which is to be converted into the string is defined. During the program execution, the interpreter will convert the int into a string as shown in the below given example:
For Example
a = 10 print(type(a)) # converting int into string convert_a = "% s" % a print(type(convert_a))
3) Using format() method
Just like the “%s” operator, you can also make use of the format() method to convert int into strings in python programming. For this method to work, you have to insert the <> placeholder in the empty string created. Later, you can call the format() method on the empty string with the integer to be converted. The below example shows the clear working of format() method for conversion of integer to string.
For Example
a = 10 print(type(a)) # converting int into string convert_a = "<>".format(a) print(type(convert_a))
4) Using F-strings
In python, F strings are used to embed a value or an expression into a string. But along with this, it is also used in the conversion of integers into strings. The syntax for F-strings is similar to that if format() method. The only difference between them is that you have to insert the variables directly into the placeholder while working with F-strings. This will make the code more clean and readable. Check out the below example for a better understanding.
For Example
a = 10 print(type(a)) # converting int into string convert_a = f'' print(type(convert_a))
Conclusion
Great work! You’ve learned so much about the integer, strings, and different methods used to convert an integer (Int) to string in python. These methods include the use of the str() method, “%s” operator, format() method, and F-strings to convert the int to string explicitly. While programming in python, there are situations where it is necessary to perform the type conversions. Therefore, these methods will give effective and faster outputs for conversion of int to string data type.
To learn more about type conversion in python, refer to our article defining 6 different ways to convert string to float.
4 Ways to Convert an Integer to a String in Python
Working with different data types is easy, until you need to combine them. Here are some techniques for using an int when all you need is a string.
Readers like you help support MUO. When you make a purchase using links on our site, we may earn an affiliate commission. Read More.
The world of programming is all about using strings and numbers. You’ll use these data types extensively, and work with them in everyday use. Sometimes you’ll need to convert between them, particularly when a language like Python is fussy about the difference.
If you are dabbling in Python, it’s useful to learn the nuances of moving from one data type to another, seamlessly.
In this article, we’ll demonstrate a few useful ways of converting a Python int to a string.
Convert a Python Number to String
Often, you might want to print a simple message which is a mix of strings and numbers. But given Python’s restrictions, you might need to adjust your approach to use the print statement correctly.
For example, Python doesn’t make it easy to print messages composed of separate parts, like:
I am Gaurav, and my age is 28 years.
Where Guarav is stored in one variable, and 28 in another.
However, Python does make integer to string conversion rather simple. To convert an int to a string, Python offers you various functions, each of which is easy to use.
Here’s a piece of code that prompts for user input:
Name = input ('Enter your name: ')
Age = 28
print ('I am ' + Name + '. I am ' + Age + ' years old.')
I am Gaurav. I am 28 years old.
Instead, Python throws the following error:
File " TypeError: can only concatenate str (not "int") to str"
This means you can’t combine a numeric and a string value using the + operator.
1. Use of str Function
The str function converts an integer into a string value. You have to use it as a prefix for any integer values.