TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Python String to Int and Back to String
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python BasicPython Tutorials

Python String to Int and Back to String

Last updated: Nov 05, 2023 6:33 pm
By Meenakshi Agarwal
Share
8 Min Read
Convert Python String to Int & Int to String with Examples
Convert Python String to Int & Int to String with Examples
SHARE

This tutorial describes various ways to convert a Python string to an int and from an integer to a string. You may often need to perform such operations in day-to-day programming. Hence, you should know them to write better programs.

Contents
1. Using Int() to Convert Python String to IntConvert an Integer from Different BasesHandling Errors/Exceptions in Conversion2. Using Str() to Convert Python Int to StringKey NotesSuggested Reading

Also, an integer can be represented in different bases, so we’ll explain that too in this post. And there happen to be scenarios where conversion fails. Hence, you should consider such cases as well and can find a full reference given here with examples.

By the way, it will be useful if you have some elementary knowledge of Python data types. If not, please go through the linked tutorial.

Python String to Int and Int to String Conversion

It is essential for a programmer to know the different conversion methods. When you read or receive data from an external source like files, it could be a number but in string format. Sometimes, we use strings to display in a styled way.

Later, when it comes to manipulating or changing the number, you need to convert the string to an integer or in an appropriate type. So, let’s now see how to convert a Python string to int and check all +/-ve scenarios.

1. Using Int() to Convert Python String to Int

Python provides a standard integer class (class ‘int’) to handle numeric operations. It comes with the int() constructor method, which can be used for converting a string to int.

Let’s check out the int() function in action with the help of an example:

"""
Python Example:
 Desc:
 Use Python int() function to convert string to int
"""

# Salary per year in string format
SalaryPerYear = '1000000'

# Test the data type of 'SalaryPerYear' variable
print("Data Type of 'SalaryPerYear': {}".format(type(SalaryPerYear)))

# Let's perform string to int conversion
SalaryPerYear = int(SalaryPerYear)

# Again, test the data type of 'SalaryPerYear' variable
print("Data Type of 'SalaryPerYear': {}".format(type(SalaryPerYear)))

Below is the result after executing the above code:

Data Type of 'SalaryPerYear': <class 'str'>
Data Type of 'SalaryPerYear': <class 'int'>

Convert an Integer from Different Bases

The default base for integer type values is 10. However, in some conditions, the string can contain a number in a different base other than 10.

A base or radix is the number of different digits or a combination of digits and letters that a system of counting uses to represent numbers.

If you wish to know more about the concept of a base, then refer to this – Base in Mathematics.

While converting such a number, you need to specify the correct base in the int() function for a successful conversion. It will assume the following syntax:

# Syntax
int(input_str, base_arg)

The allowed range for the base argument is from 2 to 36.

The point to note here is that the result would always be an integer with Base 10. Check out how to concatenate strings in Python and the below code to understand string-to-int conversion from different bases.

"""
Python Example:
 Desc:
 Use Python int() function to convert string to int from different bases
"""

# Machine Id in string format
MachineIdBase10 = '10010'
MachineIdBase8 = '23432' # 10010 => base 8 => 23432
MachineIdBase16 = '271A' # 10010 => base 16 => 271A

# Convert machine id from base 10 to 10
MACHINE_ID = int(MachineIdBase10, 10)
print("MachineID '{}' conversion from Base 10: {}".format(MachineIdBase10, MACHINE_ID))

# Convert machine id from base 8 (octal) to 10
MACHINE_ID = int(MachineIdBase8, 8)
print("MachineID '{}' conversion from Base 8: {}".format(MachineIdBase8, MACHINE_ID))

# Convert machine id from base 16 (hexadecimal) to 10
MACHINE_ID = int(MachineIdBase16, 16)
print("MachineID '{}' conversion from Base 16: {}".format(MachineIdBase16, MACHINE_ID))

When you execute the given code, it converts the strings (MACHINEIdBase) holding the same number but in different base formats. And the output value of MACHINE_ID is always in the base 10.

Convert Python string to int from different bases

Handling Errors/Exceptions in Conversion

It is also possible to get an error or exception (ValueError) while converting a string to int. It usually happens when the value is not exactly a number.

For example, you are trying to convert a string containing a number formatted using commas. Or it stores a hexadecimal value, but you missed passing the base argument.

So, you may need to handle such errors and take some preventive actions. Try to use a Python try-except block. Please check out the below example to understand.

"""
Python Example:
 Desc:
 Handle string to int conversion error/exception
"""

# Salary variable holds a number formatted using commas
Salary = '1,000,000'

try:
    print("Test Case: 1\n===========\n")
    numSalary = int(Salary)
except ValueError as ex:
    print(" Exception: \n  ", ex)
    newSalary = Salary.replace(',', '')
    print(" Action: ")
    numSalary = int(newSalary)
    print("  Salary (Int) after converting from String: {}".format(numSalary))

# MachineId
MachineId = 'F4240' # 1,000,000 => base 16 => F4240

try:
    print("\nTest Case: 2\n===========\n")
    MACHINE_ID = int(MachineId)
except ValueError as ex:
    print(" Exception: \n  ", ex)
    print(" Action: ")
    MACHINE_ID = int(MachineId, 16)
    print("  MACHINE_ID (Int) after converting from String: {}".format(MACHINE_ID))

The example includes two test cases. The first shows an error when the string contains a formatted number. On the other hand, the second fails due to an incorrect base value. After running the code, you get the following result:

Python string to int conversion valueerror

2. Using Str() to Convert Python Int to String

There is another Python standard library function called Str(). It simply takes a number value and converts it to a string.

However, Python 2.7 also had a function called Unicode() that was used to produce Unicode strings. But it isn’t available in Python 3 or later.

Check out the following examples:

"""
Python Example:
 Desc:
 Use Python str() function to convert int to string
"""

# Numeric Machine Id in Hexadecimal Format
MachineIdBase16 = 0x271A # 0x271A ==> 10010

# Convert numeric Machine Id to Integer
MACHINE_ID = str(MachineIdBase16)
print("\nMachineID ({}) conversion from Base 16: {}\n".format(hex(MachineIdBase16), MACHINE_ID))
print("MachineIdBase16 type: {} => Post CONVERT => MACHINE_ID type: {}\n".format(type(MachineIdBase16), type(MACHINE_ID)))

Below is the output snippet after executing the above code:

Convert Python int to string
Convert Python Int to String Output

Key Notes

  • Typecasting is the process of converting an object from one type to another.
  • Python automatically performs the conversion known as Implicit Type Casting.
  • Python ensures that no data loss occurs in type conversion.
  • If you call functions to convert the types, then the process is called Explicit Type Casting.
  • Explicit Casting may lead to loss of data as the user does it by force.

Suggested Reading

  • Convert Python List to Dictionary
  • Convert Python List to String

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

How to Use Extent Report in Python

10 Python Tricky Coding Exercises

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article MySQL Create User with Password Create a New User in MySQL with Password
Next Article python add lists using plus, extend, for loop, etc methods Python Add Lists

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x