杰瑞科技汇

Python中float与string如何互转?

Of course! In Python, converting between floats and strings is a very common task. Here’s a detailed guide covering both directions of conversion, along with best practices and common use cases.

Python中float与string如何互转?-图1
(图片来源网络,侵删)

Converting a Float to a String

This is useful for displaying numbers in a user-friendly way, writing them to a file, or concatenating them with other text.

The Basic Method: str()

The simplest and most direct way is to use the built-in str() function.

my_float = 3.14159
# Convert the float to a string
float_as_string = str(my_float)
print(float_as_string)
print(type(float_as_string))
# Output:
# 3.14159
# <class 'str'>

The Flexible Method: f-strings (Formatted String Literals)

Introduced in Python 3.6, f-strings are the modern and recommended way to format strings. They are fast, readable, and powerful.

pi = 3.14159
price = 99.95
# Basic conversion
print(f"The value of pi is {pi}")
# You can also control the number of decimal places
print(f"Pi to 2 decimal places: {pi:.2f}")
print(f"Price with no decimals: {price:.0f}")
# Output:
# The value of pi is 3.14159
# Pi to 2 decimal places: 3.14
# Price with no decimals: 100
  • {pi:.2f} means: format pi as a floating-point number (f) with 2 digits after the decimal point.
  • {price:.0f} means: format price as a floating-point number with 0 digits after the decimal point (it will be rounded).

The Classic Method: .format()

This was the standard before f-strings and is still widely used. It's very flexible.

Python中float与string如何互转?-图2
(图片来源网络,侵删)
pi = 3.14159
# Basic conversion
print("The value of pi is {}".format(pi))
# Control the number of decimal places
print("Pi to 4 decimal places: {:.4f}".format(pi))
# Output:
# The value of pi is 3.14159
# Pi to 4 decimal places: 3.1416

The "Old School" Method: formatting

This is an older style, inherited from C's printf. It's less common in modern Python code but you might see it in older projects.

pi = 3.14159
# %f is for floating-point numbers
print("Pi is: %f" % pi)
# To specify precision, use a period and the number
print("Pi to 2 decimal places: %.2f" % pi)
# Output:
# Pi is: 3.141590
# Pi to 2 decimal places: 3.14

Converting a String to a Float

This is necessary when you read numerical data from a file, a user input, or an API response.

The Basic Method: float()

Use the built-in float() function. It's straightforward and handles most cases.

my_string = "123.456"
# Convert the string to a float
float_number = float(my_string)
print(float_number)
print(type(float_number))
# Output:
# 123.456
# <class 'float'>

Handling Errors

If the string cannot be converted to a float (e.g., it contains letters or is empty), Python will raise a ValueError. Always handle this potential error in your code.

Python中float与string如何互转?-图3
(图片来源网络,侵删)
bad_string = "hello world"
try:
    float_number = float(bad_string)
except ValueError:
    print(f"Error: Could not convert '{bad_string}' to a float.")
# Another common error: an empty string
empty_string = ""
try:
    float_number = float(empty_string)
except ValueError:
    print(f"Error: Could not convert an empty string to a float.")
# Output:
# Error: Could not convert 'hello world' to a float.
# Error: Could not convert an empty string to a float.

Edge Cases

  • Integers in strings: float() can easily convert strings that represent whole numbers.

    int_string = "42"
    float_number = float(int_string) # This works perfectly
    print(float_number) # Output: 42.0
  • Scientific Notation: float() can also handle strings in scientific notation.

    sci_string = "1.23e-4"
    float_number = float(sci_string)
    print(float_number) # Output: 0.000123
  • Extra Whitespace: float() is smart enough to ignore leading and trailing whitespace.

    spaced_string = "  99.9  "
    float_number = float(spaced_string)
    print(float_number) # Output: 99.9

Summary Table

Task Method Example Notes
Float to String str() str(3.14) Simplest, no formatting.
f-string f"{pi:.2f}" Recommended. Fast, readable, powerful formatting.
.format() "{:.2f}".format(pi) Classic, flexible formatting.
formatting "%.2f" % pi Older style, still works.
String to Float float() float("3.14") Standard conversion. Must handle ValueError.

Complete Example: User Input

A common real-world scenario is asking a user for a number.

while True:
    user_input = input("Please enter a price: ")
    try:
        # Try to convert the user's input to a float
        price = float(user_input)
        print(f"Success! The price is: ${price:.2f}")
        break # Exit the loop if conversion is successful
    except ValueError:
        # This block runs if float() fails
        print("Invalid input. Please enter a valid number (e.g., 19.99).")
分享:
扫描分享到社交APP
上一篇
下一篇