Skip to main content

How to convert a number to a string in Python

How to convert a number to a string in Python.

Here's a step-by-step tutorial on how to convert a number to a string in Python:

Step 1: Understand the concept

Converting a number to a string means converting a numerical value to a sequence of characters. This is useful when you want to display or manipulate the number as a string, instead of as a numeric value.

Step 2: Using the str() function

The easiest way to convert a number to a string in Python is by using the built-in str() function. This function takes a number as an argument and returns its string representation.

number = 42
string_number = str(number)
print(string_number) # Output: "42"

In the above example, the str() function is used to convert the number 42 to the string "42". The resulting string is then stored in the variable string_number and printed.

Step 3: Using the format() method

Another way to convert a number to a string is by using the format() method. This method allows you to format the number as a string with specific formatting options.

number = 3.14159
string_number = "{:.2f}".format(number)
print(string_number) # Output: "3.14"

In the above example, the format() method is used to convert the number 3.14159 to the string "3.14" with two decimal places. The resulting string is then stored in the variable string_number and printed.

Step 4: Using f-strings (Python 3.6+)

If you are using Python 3.6 or later, you can also use f-strings to convert a number to a string. F-strings provide a concise and readable way to format strings.

number = 123
string_number = f"{number}"
print(string_number) # Output: "123"

In the above example, the f-string {number} is used to convert the number 123 to the string "123". The resulting string is then stored in the variable string_number and printed.

Step 5: Handling different number types

The above examples demonstrate how to convert integers and floating-point numbers to strings. However, you can also convert other number types, such as complex numbers or decimal numbers, to strings using the same methods.

complex_number = 1 + 2j
string_complex_number = str(complex_number)
print(string_complex_number) # Output: "(1+2j)"

decimal_number = Decimal("3.14159")
string_decimal_number = str(decimal_number)
print(string_decimal_number) # Output: "3.14159"

In the above examples, the str() function is used to convert a complex number and a decimal number to their respective string representations. The resulting strings are then stored in variables and printed.

That's it! You now know how to convert numbers to strings in Python.