How do you write code for type conversion in Python?

In Python, type conversion can be achieved using built-in type conversion functions. Here are some common type conversion functions and sample code:

  1. Convert the string to an integer.
string = "123"
integer = int(string)
print(integer)  # 输出: 123
  1. Convert the string to a floating-point number:
string = "3.14"
float_num = float(string)
print(float_num)  # 输出: 3.14
  1. Convert integers or floating-point numbers to strings.
number = 123
string = str(number)
print(string)  # 输出: "123"

float_num = 3.14
string = str(float_num)
print(string)  # 输出: "3.14"
  1. Convert a string to a boolean value.
string = "True"
boolean = bool(string)
print(boolean)  # 输出: True

string = "False"
boolean = bool(string)
print(boolean)  # 输出: False

注意,进行强制类型转换时必须确保原值与目标类型匹配,否则可能会出错。转换字符串为数字(整数或浮点数)时,字符串必须表示有效数字;转换字符串为布尔值时,字符串必须是“True”或“False”。

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds