>>> str(42)
'42'

>>> int('42')
42

Links to the documentation:

  • int()
  • str()

str(x) converts any object x to a string by calling x.__str__(), or repr(x) if x doesn't have a __str__() method.

Answer from Bastien Léonard on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › convert-integer-to-string-in-python
Convert integer to string in Python - GeeksforGeeks
Explanation: str(n) converts n to a string, resulting in '42'. For Python 3.6 or later, f-strings provide a quick way to format and convert values.
Published   July 12, 2025
Discussions

python - How to convert an integer to a string in any base? - Stack Overflow
So all the created strings can be converted back to Python integers by providing a string for N instead of an integer. The code works only on positive numbers by intention (there is in my eyes some hassle about negative values and their bit representations I don't want to dig into). More on stackoverflow.com
🌐 stackoverflow.com
python - How do I parse a string to a float or int? - Stack Overflow
For the reverse, see Convert integer to string in Python and Converting a float to a string without rounding it. Please instead use How can I read inputs as numbers? More on stackoverflow.com
🌐 stackoverflow.com
Convert a string to integer with decimal in Python - Stack Overflow
I have a string in the format: 'nn.nnnnn' in Python, and I'd like to convert it to an integer. ... >>> s = '23.45678' >>> i = int(s) Traceback (most recent call last): File "", line 1, in ValueError: invalid literal for int() with base 10: '23.45678' ... I could also split on '.', then subtract the decimal from zero, then add that to the whole number ... More on stackoverflow.com
🌐 stackoverflow.com
Cannot use str() to convert an int to a string.
Is maxhealth and maxhunger also integers? print(f"\nHealth: {healthstat}/{maxhealth}") More on reddit.com
🌐 r/learnpython
13
23
January 18, 2022
🌐
GeeksforGeeks
geeksforgeeks.org › python › convert-string-to-integer-in-python
Convert String to Int in Python - GeeksforGeeks
Use str.isdigit() to check if a string is entirely numeric before converting.
Published   September 11, 2025
Top answer
1 of 16
249

Surprisingly, people were giving only solutions that convert to small bases (smaller than the length of the English alphabet). There was no attempt to give a solution which converts to any arbitrary base from 2 to infinity.

So here is a super simple solution:

def numberToBase(n, b):
    if n == 0:
        return [0]
    digits = []
    while n:
        digits.append(int(n % b))
        n //= b
    return digits[::-1]

so if you need to convert some super huge number to the base 577,

numberToBase(67854 ** 15 - 102, 577), will give you a correct solution: [4, 473, 131, 96, 431, 285, 524, 486, 28, 23, 16, 82, 292, 538, 149, 25, 41, 483, 100, 517, 131, 28, 0, 435, 197, 264, 455],

Which you can later convert to any base you want

  1. at some point of time you will notice that sometimes there is no built-in library function to do things that you want, so you need to write your own. If you disagree, post you own solution with a built-in function which can convert a base 10 number to base 577.
  2. this is due to lack of understanding what a number in some base means.
  3. I encourage you to think for a little bit why base in your method works only for n <= 36. Once you are done, it will be obvious why my function returns a list and has the signature it has.
2 of 16
128

If you need compatibility with ancient versions of Python, you can either use gmpy (which does include a fast, completely general int-to-string conversion function, and can be built for such ancient versions – you may need to try older releases since the recent ones have not been tested for venerable Python and GMP releases, only somewhat recent ones), or, for less speed but more convenience, use Python code – e.g., for Python 2, most simply:

import string
digs = string.digits + string.ascii_letters


def int2base(x, base):
    if x < 0:
        sign = -1
    elif x == 0:
        return digs[0]
    else:
        sign = 1

    x *= sign
    digits = []

    while x:
        digits.append(digs[int(x % base)])
        x = int(x / base)

    if sign < 0:
        digits.append('-')

    digits.reverse()

    return ''.join(digits)

For Python 3, int(x / base) leads to incorrect results, and must be changed to x // base:

import string
digs = string.digits + string.ascii_letters


def int2base(x, base):
    if x < 0:
        sign = -1
    elif x == 0:
        return digs[0]
    else:
        sign = 1

    x *= sign
    digits = []

    while x:
        digits.append(digs[x % base])
        x = x // base

    if sign < 0:
        digits.append('-')

    digits.reverse()

    return ''.join(digits)
🌐
SheCodes
shecodes.io › athena › 2142-converting-an-integer-to-string-in-python
[Python] - Converting an Integer to String in Python - | SheCodes
Learn how to convert an integer to a string in Python by using the `str()` function or casting the integer as a string.
🌐
Python documentation
docs.python.org › 3 › library › stdtypes.html
Built-in Types — Python 3.14.3 documentation
4 days ago - Some operations are supported by several object types; in particular, practically all objects can be compared for equality, tested for truth value, and converted to a string (with the repr() function or the slightly different str() function).
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-convert-data-types-in-python-3
How To Convert Data Types in Python 3 | DigitalOcean
August 20, 2021 - 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. Let’s first look at converting integers. To convert the integer 12 to a string value, you can pass 12 into the str() method: ... When running str(12) in the Python interactive shell with the python command in a terminal window, you’ll receive the following output:
Find elsewhere
🌐
Python
docs.python.org › 3 › library › string.html
string — Common string operations
The arguments to this function is the set of all argument keys that were actually referred to in the format string (integers for positional arguments, and strings for named arguments), and a reference to the args and kwargs that was passed to vformat. The set of unused args can be calculated from these parameters. check_unused_args() is assumed to raise an exception if the check fails. ... format_field() simply calls the global format() built-in. The method is provided so that subclasses can override it. ... Converts the value (returned by get_field()) given a conversion type (as in the tuple returned by the parse() method).
Top answer
1 of 16
3116
>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545
2 of 16
605

Python2 method to check if a string is a float:

def is_float(value):
  if value is None:
      return False
  try:
      float(value)
      return True
  except:
      return False

For the Python3 version of is_float see: Checking if a string can be converted to float in Python

A longer and more accurate name for this function could be: is_convertible_to_float(value)

What is, and is not a float in Python may surprise you:

The below unit tests were done using python2. Check it that Python3 has different behavior for what strings are convertable to float. One confounding difference is that any number of interior underscores are now allowed: (float("1_3.4") == float(13.4)) is True

val                   is_float(val) Note
--------------------  ----------   --------------------------------
""                    False        Blank string
"127"                 True         Passed string
True                  True         Pure sweet Truth
"True"                False        Vile contemptible lie
False                 True         So false it becomes true
"123.456"             True         Decimal
"      -127    "      True         Spaces trimmed
"\t\n12\r\n"          True         whitespace ignored
"NaN"                 True         Not a number
"NaNanananaBATMAN"    False        I am Batman
"-iNF"                True         Negative infinity
"123.E4"              True         Exponential notation
".1"                  True         mantissa only
"1_2_3.4"             False        Underscores not allowed
"12 34"               False        Spaces not allowed on interior
"1,234"               False        Commas gtfo
u'\x30'               True         Unicode is fine.
"NULL"                False        Null is not special
0x3fade               True         Hexadecimal
"6e7777777777777"     True         Shrunk to infinity
"1.797693e+308"       True         This is max value
"infinity"            True         Same as inf
"infinityandBEYOND"   False        Extra characters wreck it
"12.34.56"            False        Only one dot allowed
u'四'                 False        Japanese '4' is not a float.
"#56"                 False        Pound sign
"56%"                 False        Percent of what?
"0E0"                 True         Exponential, move dot 0 places
0**0                  True         0___0  Exponentiation
"-5e-5"               True         Raise to a negative number
"+1e1"                True         Plus is OK with exponent
"+1e1^5"              False        Fancy exponent not interpreted
"+1e1.3"              False        No decimals in exponent
"-+1"                 False        Make up your mind
"(1)"                 False        Parenthesis is bad

You think you know what numbers are? You are not so good as you think! Not big surprise.

Don't use this code on life-critical software!

Catching broad exceptions this way, killing canaries and gobbling the exception creates a tiny chance that a valid float as string will return false. The float(...) line of code can failed for any of a thousand reasons that have nothing to do with the contents of the string. But if you're writing life-critical software in a duck-typing prototype language like Python, then you've got much larger problems.

🌐
Note.nkmk.me
note.nkmk.me › home › python
Convert a String to a Number (int, float) in Python | note.nkmk.me
April 29, 2025 - Use str() to convert a number to a string. Built-in Functions - str() — Python 3.13.3 documentation
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-convert-integers-to-strings-in-python-3
How To Convert Integers to Strings in Python 3 | DigitalOcean
September 3, 2020 - We can convert numbers to strings using the str() method. In this quick tutorial, you’ll learn how to use this method to convert integers to strings.
🌐
Reddit
reddit.com › r/learnpython › cannot use str() to convert an int to a string.
r/learnpython on Reddit: Cannot use str() to convert an int to a string.
January 18, 2022 -

Okay, so I had a crash course in Python a looooong time ago, and that's all the prior experience I have with it. I'm starting to dabble in it again, playing around with it to make a text-based game.

In this game, you have stats - Speed, Health, etc etc. Each of these is a number (an int).

I am trying to define a function names statdisplay() so that when I call on it, it prints out your stats. So, if you have a Speed of 1, and the max Speed you can increase that stat to is 5, one of the printed lines would be:

Speed: 1 / 5

This was my ORIGINAL code:

 print("\nHealth: " + healthstat + " / " + maxhealth)
 print("\nHunger: " + hungerstat + " / " + maxhunger)

 print("\nStalking Skill: " + stalkingstat + " / 5")
 print("\nHunting Skill: " + huntingstat + " / 5")

 print("\nSpeed: " + speedstat + " / 5")
 print("\nStrength: " + speedstat + " / 5")

But then I got the following error:

TypeError: can only concatenate str (not "int") to str

So I mentally facepalmed myself and looked up how to convert an int to a string, and I keep reading that you can use the str() function (I know there are other ways, but I'm taking baby steps here trying to jog my memory on how everything works before I go doing everything by what's deemed "most appropriate").

This is my NEW code with that in mind:

 print("\nHealth: " + str(healthstat) + " / " + maxhealth)
 print("\nHunger: " + str(hungerstat) + " / " + maxhunger)

 print("\nStalking Skill: " + str(stalkingstat) + " / 5")
 print("\nHunting Skill: " + str(huntingstat) + " / 5")

 print("\nSpeed: " + str(speedstat) + " / 5")
 print("\nStrength: " + str(speedstat) + " / 5")

...and yet I am still getting the following error:

TypeError: can only concatenate str (not "int") to str

I can't seem to figure out what's wrong. I do not have the str() function defined as anything else. str() also doesn't seem to come from any special libraries that I'd need to import, but maybe I'm wrong there (I tried to look it up)... the only import I currently have is "import random".

My only other thought is that maybe it's a Google Colab thing, as that's where I'm currently running my code since this wasn't anything serious and I tend to go between two different computers.

Any help would be much appreciated!

Edit: accidentally had the new code in both code boxes.

🌐
Reddit
reddit.com › r/learnpython › how to map/convert a number to string
r/learnpython on Reddit: How to map/convert a number to string
September 13, 2021 -

Hi,

I am trying to write an Icinga check in Python which checks the status of my Keepalived setup. It has several status codes.

I'd like to convert those status codes to something human readable which makes sense. So I am thinking about a dict, something like: state_codes = {0: "init", 1: "backup", 2: "master", 3: "fault", 4: "goto master", 98: "goto fault"} which contains all the possible codes.

I have a JSON object which has the data:

[{
    "data": {
        "iname": "VRRP_1",
        "state": 1,
        "wantstate": 1,
    }
}]

So the thing is I want to print something like VRRP_1 has state <STATE> and wants state <WANTSTATE>, in stead of the numbers.

How would one do that?

Thank you!

🌐
DataCamp
datacamp.com › tutorial › how-to-convert-a-string-into-an-integer-in-python
How to Convert a String Into an Integer in Python | DataCamp
November 24, 2024 - Learn how to convert Python strings to integers in this quick tutorial. ... Get your team access to the full DataCamp for business platform. Data type errors are one of the most common obstacles in Python, especially for beginners. A common data type error happens when numbers are formatted as strings, leading to miscalculations, incorrect insights, or flat-out error messages.
🌐
freeCodeCamp
freecodecamp.org › news › python-convert-string-to-int-how-to-cast-a-string-in-python
Python Convert String to Int – How to Cast a String in Python
November 29, 2021 - There are different built-in ways to convert, or cast, types in the Python programming language. In this article, you'll learn how to convert a string to an integer.
🌐
Vultr Docs
docs.vultr.com › python › built-in › str
Python str() - Convert to String | Vultr Docs
November 22, 2024 - Discover how to transform non-string data into strings and explore the impact of this transformation on data handling and presentation. Define an integer. Convert the integer into a string using str(). ... number = 123 string_number = str(number) print(string_number) print(type(string_number)) Explain Code
🌐
freeCodeCamp
freecodecamp.org › news › python-str-function-how-to-convert-to-a-string
Python str() Function – How to Convert to a String
April 4, 2023 - The str() function takes a compulsory non-string object and converts it to a string. This object the str() function takes can be a float, integer, or even a Boolean. Apart from the compulsory data to convert to a string, the str() function also ...
🌐
Reddit
reddit.com › r/learnpython › python cast a number input value as a string. what's up with that?
r/learnpython on Reddit: Python cast a number input value as a string. What's up with that?
April 19, 2023 -

Hello everyone. I'm new to Python and encountered an error while trying to make a simple BMI calculator. I'd like some help on understanding it as well to know if there's a better way of doing it. Thanks and pardon the long winded question in advance.

Here's the code:

print("BMI CALCULATOR\n")

height = input("What is your height(m)?\n")

weight = input("What is your weight(kg)?\n")

bmi = weight / (height * height)

print(height)
print(weight) 
print("\nYour bmi is: " + str(bmi))

The output:

C:\Users\USER\PycharmProjects\bmiTest\venv\Scripts\python.exe C:\Users\USER\PycharmProjects\bmiTest\main.py 
BMI CALCULATOR

What is your height(m)?
1.7
What is your weight(kg)?
72
Traceback (most recent call last):
  File "C:\Users\USER\PycharmProjects\bmiTest\main.py", line 7, in <module>
    bmi = weight / (height * height)
                    ~~~~~~~^~~~~~~~
TypeError: can't multiply sequence by non-int of type 'str'

Process finished with exit code 1

As you can see from this:

Traceback (most recent call last):
  File "C:\Users\USER\PycharmProjects\bmiTest\main.py", line 7, in <module>
    bmi = weight / (height * height)
                    ~~~~~~~^~~~~~~~
TypeError: can't multiply sequence by non-int of type 'str'

The problem seems to be that the inputs were cast as strings, even though they're numbers. As I understand it, Python casts the data type on its own without requiring me to set them. I later avoided this issue by using explicit casting like here:

print("BMI CALCULATOR")

print("\n")

height = float(input("What is your height(m)?"))

weight = int(input("What is your weight(kg)?"))

print(height)

print(weight) bmi = weight / (height * height)

print("\nYour bmi is: " + str(bmi))

The output:

C:\Users\USER\PycharmProjects\bmiCalculator\venv\Scripts\python.exe C:\Users\USER\PycharmProjects\bmiCalculator\main.py 
BMI CALCULATOR

What is your height(m)?
1.7
What is your weight(kg)?
72
1.7
72

Your bmi is: 24.913494809688583

Process finished with exit code 0

But I feel like I'm doing something wrong if I have to do more work to skirt around a feature that's supposed to save time. So again, why does python cast the inputs of weight and height as string, eventhough they're numbers? And is there a better way of doing it?

Top answer
1 of 7
26
input always returns a str type even if your user enters only numbers. I agree it seems odd that Python doesn’t duck written numbers into actual ints, but wrapping your call to input inside a call to int() is the most common solution if you need user input to be treated as ints. It will bite you once or twice and then you’ll stop caring because it turns out you never use input when actually writing programs.
2 of 7
17
This is desired behavior. When your user enters anything at all via a terminal (or even if it's text read from a file), your program sees characters being entered. This is most obvious when it's a series of alpha characters like "abc", but the character "1" and the integer 1 are not the same. When anything is entered via the keyboard, it's a character. This is true for most, if not all, other programming languages too. Sure, I can see why you are initially thrown off by this. If your user presses the key for 5, you might expect your program to immediately do some math with that entry. But in fact, they have entered the character "5". Why not have it default to an int? Well, what if they entered "abc123". Would you want the data type to suddenly change during the user's input? What about "a1b2c3". If you haven't already, do some reading about ASCII. That will really help you understand how everything on a computer is a number. A single character is a byte. In fact the character "1" is actually the number 49, which your computer stores as binary. In some languages, you can print the character "1", but specify to print as a decimal number, and you'll se 49 as the output. Python obscures this away from you, which is handy, but also causes confusion sometimes. Anything that you get with input() will always be a string. It could even be an empty string.
🌐
Medium
medium.com › @Doug-Creates › convert-string-to-float-or-int-in-python-0d93ce89d7b1
Convert String to Float or Int in Python | by Doug Creates | Medium
March 24, 2024 - They start by collecting sample inputs from potential users, which include a mix of whole numbers, decimal numbers, and non-numeric strings. The team then writes a Python script that checks each string’s format. If the string represents a whole number, the script uses the int() function to convert it to an integer.