Easy Python Number & String Conversion — Beginner’s Guide

1. Introduction

Python is a programming language loved by developers from beginners to advanced users. Converting between numbers and strings is an essential skill for data processing and output. In this article, we explain in detail how to convert numbers to strings in Python and vice versa. We also present practical use cases and examples of implementing error handling.

2. Basic Data Types in Python

Python’s data types are very flexible, allowing you to easily work with different types such as numbers and strings. In this section, we’ll learn the basics of numeric types and string types.

Numeric Types

In Python, numeric types are broadly categorized into two classes:
  • Integer type (int): e.g.) 10, -5, 0
  • Floating-point type (float): e.g.) 3.14, -0.001, 2.0

String type (str)

The string type is a data type that handles sequences of characters. In Python, strings are defined by enclosing them in single quotes'or double quotes". Example:
name = "Python"
greeting = 'Hello'

Checking Data Types

In Python, you can check a variable’s data type using the type() function.
num = 10
text = "string"
print(type(num))  # <class 'int'>
print(type(text))  # <class 'str'>

3. How to Convert Numbers to Strings

Converting numbers to strings allows you to perform string operations. This section introduces the main conversion methods and examples of their use.

Conversion using the str() function

In Python, you can easily convert numbers to strings using the str() function.
num = 123
text = str(num)
print(text)  # "123"
print(type(text))  # <class 'str'>

Conversion Using Format Specification

In Python, you can convert numbers to strings using the format() method or f-strings.
  • format() method:
num = 123.456
text = "The number is {:.2f}".format(num)
print(text)  # "The number is 123.46"
  • f-strings:
num = 123.456
text = f"The number is {num:.2f}"
print(text)  # "The number is 123.46"

4. How to Convert Strings to Numbers

Converting strings to numbers enables numeric operations such as calculations. This chapter introduces conversion methods using the int() and float() functions.

Convert to integers with the int() function

When converting to an integer, the string must be in an integer format.
text = "100"
num = int(text)
print(num)  # 100
print(type(num))  # <class 'int'>

Convert to floating-point numbers using the float() function

To handle numbers that include a decimal point, use the float() function.
text = "123.45"
num = float(text)
print(num)  # 123.45
print(type(num))  # <class 'float'>

Error Handling

If a string cannot be converted to a number, an error will occur. Therefore, it’s recommended to use try-except for exception handling.
text = "abc"
try:
    num = int(text)
    print(num)
except ValueError:
    print("Cannot convert to a number")
侍エンジニア塾

5. Concatenating Numbers and Strings

When concatenating numbers and strings, you must convert numbers to strings. This chapter covers efficient ways to concatenate.

str() function-based concatenation

num = 42
text = "The answer is " + str(num) + ""
print(text)  # "The answer is 42"

Concatenation Using f-strings

Using f-strings lets you write more concisely.
num = 42
text = f"The answer is {num}"
print(text)  # "The answer is 42"

6. Handling Special Cases

Conversion with a Specified Base

When converting a string to an integer with a specified base, pass the second argument to the int() function.
binary = "1010"
num = int(binary, 2)  # Interpreted as binary
print(num)  # 10

Converting Kanji Numerals and Full-Width Digits

You can use Python’s unicodedata module to convert full-width digits and kanji numerals into numbers.
import unicodedata
text = "123"
normalized = unicodedata.normalize('NFKC', text)
num = int(normalized)
print(num)  # 123

7. Summary

This article explained how to convert between numbers and strings in Python.
  • To convert numbers to strings, use the str() function or format specifiers.
  • To convert strings to numbers, use the int() and float() functions.
  • In special cases, utilize base specification and the unicodedata module.
Converting between numbers and strings is a fundamental part of data processing and an essential skill for practical programming. Use this article as a reference to help you write more efficient code!
侍エンジニア塾