How to convert data types in Python

WBOY
Release: 2023-05-01 11:37:14
forward
5752 people have browsed it

1. The role of converting data types

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.

2. Functions for converting data types

##str( x )Convert object x to stringrepr(x )Convert object x to expression stringeval(str)Used to calculate a valid Python expression in a string and return an objecttuple(s )Convert sequence s into a tuplelist(s )Convert sequence s into a listchr(x )Convert an integer to a Unicode character ord(x )Convert a character Convert an integer to a hexadecimal string for its ASCII integer value##hex(x )oct(x )bin(x )3. Quick experience
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 an integer to an octal string
Convert an integer to a binary String

Requirements: input receives user input, the user inputs "1", and converts this data 1 into an integer.

# 1. 接收用户输入
num = input('请输入您的幸运数字:')

# 2. 打印结果
print(f"您的幸运数字是{num}")


# 3. 检测接收到的用户输入的数据类型 -- str类型
print(type(num))

# 4. 转换数据类型为整型 -- int类型
print(type(int(num)))
Copy after login

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)))
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!