Q: The data input() receives from the user are all string types. If the user inputs 1, what should I do if I want to get the integer type?
Answer: Just convert the data type, that is, convert the string type into an integer type.
Function | Description |
---|---|
int( x [,base ]) | Convert x to an integer |
float(x ) | Convert x to a floating point number |
complex(real [,imag ]) | Create a complex number, real is the real part and imag is the imaginary part |
Convert object x to string | |
Convert object x to expression string | |
Used to calculate a valid Python expression in a string and return an object | |
Convert sequence s into a tuple | |
Convert sequence s into a list | |
Convert an integer to a Unicode character | |
Convert a character Convert an integer to a hexadecimal string for its ASCII integer value | |
Convert an integer to an octal string | |
Convert an integer to a binary String |
# 1. 接收用户输入 num = input('请输入您的幸运数字:') # 2. 打印结果 print(f"您的幸运数字是{num}") # 3. 检测接收到的用户输入的数据类型 -- str类型 print(type(num)) # 4. 转换数据类型为整型 -- int类型 print(type(int(num)))
4. Experiment
# 1. float() -- 转换成浮点型 num1 = 1 print(float(num1)) print(type(float(num1))) # 2. str() -- 转换成字符串类型 num2 = 10 print(type(str(num2))) # 3. tuple() -- 将一个序列转换成元组 list1 = [10, 20, 30] print(tuple(list1)) print(type(tuple(list1))) #学习中遇到问题没人解答?小编创建了一个Python学习交流群:725638078 # 4. list() -- 将一个序列转换成列表 t1 = (100, 200, 300) print(list(t1)) print(type(list(t1))) # 5. eval() -- 将字符串中的数据转换成Python表达式原本类型 str1 = '10' str2 = '[1, 2, 3]' str3 = '(1000, 2000, 3000)' print(type(eval(str1))) print(type(eval(str2))) print(type(eval(str3)))
The above is the detailed content of How to convert data types in Python. For more information, please follow other related articles on the PHP Chinese website!