Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Converting Integer to String in Python

#1
Converting Integer to String in Python

Quick Fix: Python’s built-in str(x) method converts an integer object x to a string object by using the x.__str__() method.

❖ Introduction


Problem Formulation: Given a string object in Python, what are the ways to convert it to an Integer type?

Example:

# This is an integer
x = 13
print("x is of type", type(x))
# Converting integer to string
y = str(x)
print("y is of type", type(y))

Output:

x is of type <class 'int'>
y is of type <class 'str'>

Let us have a look at an example where converting an integer becomes a defining factor in your code.

Scenario: Concatenate a string and an integer.

version = 3
lang = 'Python'
print(lang+version) # Desired Output: Python3

Actual Output:

Traceback (most recent call last): File "D:/PycharmProjects/PythonErrors/int2string.py", line 3, in <module> print(version+lang)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Explanation: The usage of the + operator to concatenate a string and integer is not allowed in Python. Thus, Python throws a TypeError: unsupported operand type(s) for +: 'int' and 'str' in this case.

The solution to this problem is to convert the integer object to a string object and then concatenate the two strings as shown in the solution below.

Solution:

version = 3
lang = 'Python'
print(lang+str(version)) # Output: Python3

Before moving on to the solutions, I highly recommend you to go through the type conversion techniques explained in this tutorial.

Now, without further ado, let us dive into the solutions to our mission-critical question – “How to convert an integer to a string in Python?

? Method 1: Using The str() Method


Python’s built-in str(x) function converts the object x to a string using the x.__str__() method or, if non-existent, the repr(x) built-in function to obtain the string conversion.

  • The str() method returns a string type of an object. The object can be char, integer, etc. The str() method returns a string type of an object. The object can be char, integer, or a string.

Syntax:

str(object)
Python str() Function Built-in -- Explanation

Example:

num_int = 2500
num_str = str(num_int)
print("num_str: ", num_str)
print("Type of num_float: ", type(num_int))
print("Type of num_str: ", type(num_str))

Output:

num_str: 2500
Type of num_float: <class 'int'>
Type of num_str: <class 'str'>

? Method 2: Using The format() Function


We can use the format() method in Python, for converting integers to strings. This method permits you to set placeholders inside a string and then convert any other data type (integer, float) to a string and fill the placeholders. Curly brackets ‘{} ’ are used to define the placeholders.

Syntax

"{}" .format (int)

Example:

# This is an integer
y = 20
print("The value of y is", y)
print("Initially the number is of type", type(y)) # Converting integer to string using format()
y = "{}".format(y)
print("The number is of type", type(y), "after conversion.")

Output:

The value of y is 20
Initially the number is of type <class 'int'>
The number is of type <class 'str'> after conversion.

? Method 3: Using String Conversion ‘%s


Python utilizes two unique styles of string formatting: the oldest style that depends on the modulo operator (%), and the more up-to-date Python 3 style that utilizes the format function. (As seen in method 2).

  • Python’s old standard string conversion method uses the modulo operator (the percent sign %) as a unique symbol to demonstrate the various types of formats.
  • The conversion specifiers, for example, %s and %d show up in the format string as placeholders.
  • These specifiers direct how the operation will format the values.
  • %s is used for string conversion.

Example:

# This is an integer
no = 2
print("Initially the value of the number is", no)
print("The number is of type", type(no)) # Converting integer to string using %s
conv = "% s" % no
print("The number is of type", type(conv), "after conversion.")

Output:

Initially the value of the number is 2
The number is of type <class 'int'>
The number is of type <class 'str'> after conversion.

? Method 4: Using f-strings


f-strings are supported in Python 3.6 or higher versions. It is represented by string literals that have an f as a prefix and curly braces containing the expressions. The variables in the expression get replaced by the values during evaluation at runtime.

Syntax:

f'{ int }'

Example:

# This is an integer
x = 50
print("The value of the number is", x)
print("The number is of type", type(x)) # Converting integer to string using f strings
y = f'{x}'
print("The value of the number remains", y)
print("The number is of type", type(y), "after conversion.")

Output:

The value of the number is 50
The number is of type <class 'int'>
The value of the number remains 50
The number is of type <class 'str'> after conversion.

? Method 5: Using a Custom Method


Another workaround, that deserves to be mentioned is a user-defined custom method that converts the integer object to a string object as shown in the following example.

Example:

def convert(x, type_): x = type_(x) return x
num = 25
print("Initially type of num : ", type(num))
print("Type of num after conversion: ", type(convert(num, str)))

Output:

Initially type of num : <class 'int'>
Type of num after conversion: <class 'str'>

❖ Conclusion


Thus, the following methods can be used to convert an integer to a string in Python:

  •  The str() built-in method.
  •  The format() Function.
  •  String Conversion using ‘%s‘.
  •  Using f-strings.
  •  Defining a Custom function.

I hope this article helped you. Please subscribe and stay tuned for more interesting articles in the future.

Authors
?
SHUBHAM SAYON
?
RASHI AGARWAL

Recommended Course:

  • Do you want to master the most popular Python IDE fast?
  • This course will take you from beginner to expert in PyCharm in ~90 minutes.
  • For any software developer, it is crucial to master the IDE well, to write, test and debug high-quality code with little effort.
The Complete Guide to PyCharm

Join the PyCharm Masterclass now, and master PyCharm by tomorrow!

The post Converting Integer to String in Python first appeared on Finxter.



https://www.sickgaming.net/blog/2021/04/...in-python/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] Python Regex to Return String Between Parentheses xSicKxBot 0 15 05-04-2021, 05:21 PM
Last Post: xSicKxBot
  [Tut] How To Check if One String is a Subsequence of Another? xSicKxBot 0 31 04-22-2021, 05:00 PM
Last Post: xSicKxBot
  [Tut] How To Remove All Non-Alphabet Characters From A String? xSicKxBot 0 31 04-17-2021, 09:56 PM
Last Post: xSicKxBot
  [Tut] How to Check if a Python String Contains Only Digits? xSicKxBot 0 34 04-12-2021, 12:23 PM
Last Post: xSicKxBot
  [Tut] How to Convert a String List to an Integer List in Python xSicKxBot 0 41 04-09-2021, 01:50 PM
Last Post: xSicKxBot
  [Tut] How to Convert a Float List to a String List in Python xSicKxBot 0 39 04-07-2021, 02:53 PM
Last Post: xSicKxBot
  [Tut] Python String to Float Conversion xSicKxBot 0 40 04-01-2021, 11:07 PM
Last Post: xSicKxBot
  [Tut] How to Convert Hex String to Integer in Python xSicKxBot 0 44 03-30-2021, 01:04 PM
Last Post: xSicKxBot
  [Tut] Python String zfill() xSicKxBot 0 46 03-22-2021, 06:30 PM
Last Post: xSicKxBot
  [Tut] How to Create a Tuple from a String and a List of Strings xSicKxBot 0 51 03-13-2021, 09:55 AM
Last Post: xSicKxBot

Forum Jump:

[-]
Active Threads
News - F4F Reveals Banjo-Kazooie Mumbo J...
Last Post: xSicKxBot
Yesterday 11:16 PM
» Replies: 0
» Views: 3
News - Review Roundup For Spiral: From T...
Last Post: xSicKxBot
Yesterday 11:16 PM
» Replies: 0
» Views: 16
Black Ops 2 Box and Name ESP | Fully Ext...
Last Post: Jaesanta
Yesterday 10:34 PM
» Replies: 55
» Views: 20949
[Tut] [FANG KILLER ICP] Will the Interne...
Last Post: xSicKxBot
Yesterday 05:04 PM
» Replies: 0
» Views: 9
(Indie Deal) Star Wars, No Man's Sky, Co...
Last Post: xSicKxBot
Yesterday 05:04 PM
» Replies: 0
» Views: 10
Unity Mega Bundle 2021 On Now
Last Post: xSicKxBot
Yesterday 05:04 PM
» Replies: 0
» Views: 11
Mobile - Noob Army Tycoon codes – free m...
Last Post: xSicKxBot
Yesterday 05:04 PM
» Replies: 0
» Views: 10
AppleInsider - UK repair firm fined $147...
Last Post: xSicKxBot
Yesterday 05:04 PM
» Replies: 0
» Views: 10
Microsoft - Securing a new world of hybr...
Last Post: xSicKxBot
Yesterday 05:04 PM
» Replies: 0
» Views: 9
Fedora - Using Ansible to configure Podm...
Last Post: xSicKxBot
Yesterday 05:04 PM
» Replies: 0
» Views: 10

[-]
Twitter

Copyright © SickGaming.net 2012-2020