>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545
Answer from Harley Holcombe on Stack Overflow
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 - In Python, you can convert a string (str) to a number using int() for an integer or float() for a floating-point number. Convert a string to int: int() Convert a string to float: float() Convert a bin ...
Discussions

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
Convert integer to string in Python - Stack Overflow
This has been deprecated in python ... docs.python.org/3.0/whatsnew/3.0.html#removed-syntax 2015-07-13T18:47:08.057Z+00:00 ... For someone who wants to convert int to string in specific digits, the below method is recommended. ... For more details, you can refer to Stack Overflow question Display number with leading ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Python cast a number input value as a string. What's up with that?
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. More on reddit.com
๐ŸŒ r/learnpython
23
4
April 19, 2023
How to map/convert a number to string
print(f'{d["iname"]} has state {d["state"]} and wants state {d["wantstate"]}') Like this, where d is your dictionary. More on reddit.com
๐ŸŒ r/learnpython
4
0
September 13, 2021
๐ŸŒ
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:
๐ŸŒ
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 - To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed.
๐ŸŒ
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.
๐ŸŒ
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 - For more on data types, read this Data Structures in Python tutorial on DataCamp. Correct data types are essential for accurate calculations. Consider the following example. Letโ€™s assume we have two numbers 5 and 10 which are strings. If we add them together, the answer would be 510, since they are being treated as strings that get concatenated with the + operator. To get the accurate answer (in this case 15), they would need to be converted to integers before calculating the sum.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ convert-string-to-integer-in-python
Convert String to Int in Python - GeeksforGeeks
Convert String to Int means changing a value written as text (string) into a number (integer) so you can do math with it. The simplest way to convert a string to an integer in Python is by using the int() function.
Published ย  September 11, 2025
Find elsewhere
๐ŸŒ
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 - This is a recipe from PythonFleek. Get the free e-book today! ... Convert strings to numerics, ensuring error-free, precise parsing for advanced computational tasks. def parse_string_to_number(s): try: return int(s) except ValueError: try: return float(s) except ValueError: return None
๐ŸŒ
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
๐ŸŒ
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.
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ library โ€บ stdtypes.html
Built-in Types โ€” Python 3.14.3 documentation
4 days ago - Applying the reverse conversion to 3740.0 gives a different hexadecimal string representing the same number: ... The complex type implements the numbers.Complex abstract base class. complex also has the following additional methods. ... Class method to convert a number to a complex number.
๐ŸŒ
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!

๐ŸŒ
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.
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)
๐ŸŒ
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
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ string.html
string โ€” Common string operations
If there is no literal text (which ... string. If there is no replacement field, then the values of field_name, format_spec and conversion will be None. The value of field_name is unmodified and auto-numbering of non-numbered positional fields is done by vformat(). ... Given field_name, convert it to an object ...
๐ŸŒ
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.