Câu hỏi phỏng vấn Python
Câu hỏi

How the string does get converted to a number?

Câu trả lời

In Python, converting a string to a number is a common operation that can be achieved using built-in functions, primarily int() for integers and float() for floating-point numbers. Here's a detailed explanation of how these conversions are handled:

Converting String to Integer

To convert a string that represents an integer value, you can use the int() function. This function takes the string as input and returns its integer representation.

Syntax:

python Copy
int(string)

Example:

python Copy
s = "123"
number = int(s)
print(number)  # Output: 123

If the string does not represent a valid integer (e.g., contains non-numeric characters or is a floating-point number), a ValueError will be raised[4][5][6].

Converting String to Floating-Point Number

For strings that represent floating-point numbers, the float() function is used. This function converts the string into a floating-point number.

Syntax:

python Copy
float(string)

Example:

python Copy
s = "123.456"
number = float(s)
print(number)  # Output: 123.456

Like with int(), if the string does not represent a valid floating-point number, a ValueError will be thrown[4][5][6].

Handling Errors

When converting strings to numbers, it's common to handle potential ValueError exceptions using a try-except block, especially when the input is not guaranteed to be numeric.

Example:

python Copy
s = "abc"
try:
    number = int(s)
except ValueError:
    print("The string does not contain a valid integer.")

Special Cases and Considerations

  • Binary, Octal, and Hexadecimal Conversions: The int() function can also convert strings in binary, octal, or hexadecimal format to an integer by specifying the base.

    Example:

    python Copy
    binary_string = "1010"
    number = int(binary_string, 2)  # Base 2 for binary
    print(num...
junior

junior

Gợi ý câu hỏi phỏng vấn

middle

What does an x = y or z assignment do in Python?

middle

How can I create a copy of an object in Python?

middle

Explain the UnboundLocalError exception and how to avoid it?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào