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:

int(string)

Example:

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:

float(string)

Example:

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:

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:

    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

senior

What is the difference between a function decorated with @staticmethod and one decorated with
@classmethod ?

junior

What are the rules for local and global variables in Python?

middle

What does the Python nonlocal statement do (in Python 3.0 and later)?

Bình luận

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

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