Python数据结构(数字和字符串)
数字、字符串、列表、元组、字典
数字
Python Number 数据类型用于存储数值。
Python Number 数据类型用于存储数值,包括整型、长整型、浮点型、复数。
(1)Python math 模块:Python 中数学运算常用的函数基本都在 math 模块
import math print(math.ceil(4.1)) #返回数字的上入整数 print(math.floor(4.9)) #返回数字的下舍整数 print(math.fabs(-10)) #返回数字的绝对值 print(math.sqrt(9)) #返回数字的平方根 print(math.exp(1)) #返回e的x次幂
5 4 10.0 3.0 2.718281828459045
(2)Python随机数
首先import random,使用random()方法即可随机生成一个[0,1)范围内的实数
import random ran = random.random() print(ran)
0.4536929444397546
randint()生成一个随机整数
ran = random.randint(1,20) print(ran)
18
字符串
字符串连接:+
a = "Hello " b = "World " print(a + b)
Hello World
重复输出字符串:*
print(a * 3)
Hello Hello Hello
通过索引获取字符串中字符[]
print(a[0])
H
字符串截取[:] 牢记:左闭右开
print(a[1:4])
ell
判断字符串中是否包含给定的字符: in, not in
print('e' in a) print('e' not in a)
True False
join():以字符作为分隔符,将字符串中所有的元素合并为一个新的字符串
new_str = '-'.join('Hello') print(new_str)
H-e-l-l-o
字符串单引号、双引号、三引号
print('Hello World!') print("Hello World!")
Hello World!
Hello World!
转义字符 \
print("The \t is a tab") print('I\'m going to the movies')
The is a tab I'm going to the movies
三引号让程序员从引号和特殊字符串的泥潭里面解脱出来,自始至终保持一小块字符串的格式是所谓的WYSIWYG(所见即所得)格式的。
print('''I'm going to the movies''') html = ''' <HTML><HEAD><TITLE> Friends CGI Demo</TITLE></HEAD> <BODY><H3>ERROR</H3> <B>%s</B><P> <FORM><INPUT TYPE=button VALUE=Back ONCLICK="window.history.back()"></FORM> </BODY></HTML> ''' print(html)
I'm going to the movies <HTML><HEAD><TITLE> Friends CGI Demo</TITLE></HEAD> <BODY><H3>ERROR</H3> <B>%s</B><P> <FORM><INPUT TYPE=button VALUE=Back ONCLICK="window.history.back()"></FORM> </BODY></HTML>

浙公网安备 33010602011771号