Concepts / Converting to Strings with str()

Converting to Strings with str()

float() converts integers and numeric strings to floating-point numbers, adding decimal representation where none existed.

  • Programming
Interactive lab

Try it: Type conversion: int(), float(), str(), bool()

Exactly how int(), int(text, base), float(), str() and bool() turn a value into another type: Python's real parsing rules for text (whitespace, sign, underscores, 0x/0o/0b prefixes, inf/nan, exponents) and its truthiness rules.

How it works

  1. int(text) strips surrounding whitespace, allows one sign, then reads digits (underscores only between digits); any other character raises ValueError: invalid literal for int().
  2. int(text, base) reads digits in that base; base 0 takes the base from a 0x / 0o / 0b prefix like a Python literal.
  3. float(text) accepts decimals like '.5', '5.', '1e3' and the names inf, infinity and nan, then rounds to the nearest double.
  4. int() of a float truncates toward zero; str() gives the printed form (repr digits for floats).
  5. bool() is truthiness: '', 0, 0.0 and None are False; every non-empty string — even '0' or 'False' — is True.

Default run (8 steps): int(' -0x_1F ', 0): the argument is a str of 10 characters. … int(' -0x_1F ', 0) → -31

Simplified: The argument is a Python literal typed as text (ASCII only; escapes \t \n \r). Unicode digits and bytes arguments are not modelled.

Educational simulation

Loading the simulation…

One Value, Three Representations

A value can be converted into different forms depending on what a calculation or display needs. float() produces a floating-point number, int() produces an integer, and str() represents a value as text. The conversion function does not merely rename the original value: it determines how the result is represented and what information is retained.

FunctionResultImportant behavior
int()IntegerRemoves the decimal portion instead of rounding.
float()Floating-point numberPreserves fractional values and adds decimal representation when needed.
str()StringRepresents the value as text.

The three conversion functions produce different kinds of results.

Following a Value Through Conversion

Start with the value 7. Converting it with float() gives a floating-point representation, so the result has decimal notation even though the original value did not. Converting it with str() changes the value into text. Converting it with int() keeps it as an integer. These operations answer different questions: should the result support fractional numeric calculations, remain an integer, or be treated as text?

7int(7)integer resultfloat(7)floating-point resultstr(7)text resultinteger conversionfloating-point conversionstring conversion
How does the same input change when converted to an integer, a floating-point number, or a string?

What Each Function Preserves

float() is used when a value needs to be in floating-point form. It converts integers and numeric strings to floating-point numbers. For an integer such as 7, float() adds decimal representation where none existed. For a numeric string such as 7.25, float() converts the text into a floating-point number and preserves its fractional value.

int() has a different behavior. When it receives a floating-point value, it truncates the decimal portion. Truncation means chopping off everything after the decimal point; it does not mean choosing the nearest integer. Therefore, 3.99999 becomes 3, not 4. The same rule applies regardless of how large the decimal portion is.

str() is the conversion to use when the result should be text rather than a numeric value. This makes it different from int() and float(): those functions produce numeric forms, while str() represents the value as a string.

Decimal Portions After int()

Worked example

Predicting truncation

Determine the integer result when int() receives 3.9, -2.7, and 5.0.

  1. 1
    3.9

    int() removes the decimal portion, so the result is 3 rather than 4.

  2. 2
    -2.7

    int() removes the decimal portion, so the result is -2 rather than a rounded value.

  3. 3
    5.0

    The decimal portion is zero, so removing it leaves 5.

Result

int(3.9) produces 3, int(-2.7) produces -2, and int(5.0) produces 5.

3.93-2.7-25.05int()int()int()
What happens to the decimal portion when int() converts 3.9, -2.7, and 5.0?

Acceptable Inputs and Errors

int() works with floating-point values and whole-number strings. It raises an error for decimal strings and for invalid input. For example, a string containing a decimal representation cannot be passed directly to int() according to the source behavior described here. To convert a decimal string such as '3.14' to an integer, first convert the string to a floating-point number and then convert that result to an integer: int(float('3.14')). The intermediate float conversion handles the decimal string; the later int conversion truncates the decimal portion.

float() accepts integers and numeric strings. If the input string does not represent a valid number, float() raises a ValueError. This distinction matters when processing user input: text that looks like a number can be converted, but nonnumeric text cannot be treated as a floating-point number by float().

Input valueIntegerint() resultDecimal numberfloat() resultNumeric stringValueErrorNonnumeric stringinspectinspectinspectinspectint()float()int(), truncatefloat(), preserve fractionfloat()float()
How does each function process integers, decimal numbers, numeric strings, and nonnumeric strings?

Mistakes in Conversion Choices

  • Common mistake

    Expecting int() to round a decimal value.

    What it looks like
    Converting 3.99999 with int()
    Why it fails

    int() truncates by removing the decimal portion; it does not round to the nearest integer.

    Do this instead

    Expect the result 3.

  • Common mistake

    Passing a decimal string directly to int().

    What it looks like

    Converting the string '3.14' directly with int()

    Why it fails

    int() works with whole-number strings, but a decimal string raises an error.

    Do this instead

    Convert the string to float first, then convert that result to int.

  • Common mistake

    Treating str() as a numeric conversion.

    What it looks like

    Using str() when a value is needed for numeric calculations

    Why it fails

    str() produces text, whereas int() and float() produce numeric forms.

    Do this instead

    Use int() for an integer result or float() for a floating-point result.

  • Common mistake

    Assuming float() accepts every string.

    What it looks like

    Passing a string that does not represent a valid number to float()

    Why it fails

    float() raises a ValueError for a string that is not a valid number.

    Do this instead

    Check that the input string represents a number before relying on float() conversion.

Choosing the Conversion

Choose the function based on the form you need after conversion. Use float() when fractional values must be preserved or when an integer needs floating-point form. Use int() when an integer result is required and truncating any decimal portion is acceptable. Use str() when the value must be represented as text. When converting user input, remember that input commonly arrives as strings, so numeric calculations require an appropriate numeric conversion rather than str().

NeedFunctionResulting behavior
Floating-point formfloat()Converts integers and numeric strings to floating-point numbers.
Integer formint()Converts supported values and truncates decimal portions.
Text formstr()Represents the value as a string.

A quick decision guide for the three conversion functions.

Check Your Prediction

MEDIUM

For each case, predict the result or error before checking: float(7), float('7.25'), int(3.9), int(5.0), int('3.14'), and str(7). Then classify each successful result as an integer, floating-point number, or string.

Hints
  • float() converts integers and numeric strings to floating-point numbers.
  • int() removes the decimal portion instead of rounding.
  • A decimal string must be converted to float before it can be converted to int.
  • str() produces text rather than a numeric result.
Worked example

Practice answers

Classify the results of float(7), float('7.25'), int(3.9), int(5.0), int('3.14'), and str(7).

  1. 1
    float(7)

    An integer is converted to floating-point form, adding decimal representation.

  2. 2
    float('7.25')

    A numeric string is converted to a floating-point number, preserving its fractional value.

  3. 3
    int(3.9)

    The decimal portion is truncated, producing 3.

  4. 4
    int(5.0)

    The decimal portion is removed, producing 5.

  5. 5
    int('3.14')

    A decimal string is not accepted directly by int(), so this conversion raises an error.

  6. 6
    str(7)

    The value is represented as text.

Result

The cases produce floating-point results, truncated integer results, an error for the decimal string passed directly to int(), and a string result for str(7).

Key Takeaways

  1. 1
    float() converts integers and numeric strings to floating-point numbers and preserves fractional values.
  2. 2
    int() truncates decimal portions; it does not round them.
  3. 3
    int() accepts floats and whole-number strings but raises an error for decimal strings or invalid input.
  4. 4
    float() raises a ValueError when a string does not represent a valid number.
  5. 5
    str() represents a value as text, unlike int() and float(), which produce numeric forms.

At a glance

  • Use float() for floating-point results and to preserve fractional values.
  • Use int() for integer results, remembering that it truncates rather than rounds.
  • Convert a decimal string to float before converting it to int.
  • Use str() when the result should be text rather than a number.
  • Invalid numeric strings cause conversion errors with the numeric conversion functions.

Related concepts

More concepts starting with C