-
Python中的缩进是有功能的,一般为tab键或4个空格(1个空格也可以,但相同代码块中的缩进字符必须保持一致),缩进错误会导致报错
-
Python中用#进行单行注释,用””” “””进行多行注释
-
Python不需要声明变量和变量类型,直接对变量赋值即可,赋值后可更改变量类型
1#创建变量
2x=5
3#查看变量类型
4print(type(x))
5#更改变量类型
6x=float(x)
7print(type(x)) -
Python中的变量名要求:只能包括数字、字母及下划线;不能以数字开头;区分大小写
-
同时给多个变量赋值
1#同时给多个变量赋不同的值
2x,y,z="a","b","c"
3#同时给多个变量赋相同的值
4x=y=z="a"
5#同时给多个变量赋列表里的值
6fruits=["orange","apple","cherry"]
7x,y,z=fruits -
用print()进行变量的输出
1#输出单个变量
2x="hello world"
3print(x)
4#输出多个变量,并以空格分隔
5x="hello"
6y="world"
7print(x,y)#结果为hello world
8print(x+y)#结果为hello world
9#输出两个数值型变量
10x=5
11y=10
12print(x,y)#结果为5 10
13print(x+y)#结果为15
14#同时输出数值型变量和字符型变量
15x="a"
16y=5
17print(x,y)#结果为a 5
18print(x+y)#会报错 -
全局变量和局部变量
在函数外部创建的变量为全局变量,在函数内部创建的变量为局部变量,全局变量均可访问,局部变量只有在声明其的函数内部可以访问
如果全局变量与局部变量的变量名相同,则在函数内用该变量名访问时为局部变量,在函数外访问时为全局变量
如果在函数内部想要创建全局变量,需借助global关键词
1#全局变量与局部变量拥有相同变量名
2x="a"
3def myfunc():
4 x="b"
5 print(x)
6
7myfunc()#结果为b
8print(x)#结果为a
9
10#在函数内部声明全局变量
11def myfunc():
12 global x
13 x="a"
14
15print(x)#结果为a -
Python中的数据类型
Text Type:str
Numberic Types:int,float,complex
Sequence Types:list、tuple、range
Mapping Type:dict
Set Types:sert、frozenset
Boolean Type:bool
Binary Types:bytes,bytearray、memoryview
用type()获取变量的数据类型
不同的数据类型,赋值的方式不同,利用函数可强制指定数据类型
1x="hello"#str
2x=5#int
3x=5.5#float
4x=2z#complex
5x=["a","b"]#list
6x=("a","b")#tuple
7x=range(6)#range,结果为0-5
8x={"name":"John","age":36}#dict
9x={"a","b"}#set
10x=frozenset({"a","b"})#forzenset
11x=True#bool
12x=b"hello"#bytes,结果为b'Hello'
13x=bytearry(5)#bytearry,结果为bytearray(b'x00x00x00x00x00')
14x=memoryview(bytes(5))#memoryview,结果为<memory at 0x00D58FA0> -
Python中的随机数通过random模块中的randrange实现
1#从1-9中随机产生1个数字
2import random
3print(random.randrange(1,10))#注意Python中的从A到B都是含头不含尾 -
Python中的字符串以数组的形式储存,因此可通过类似的方式访问字符串中的单个字符以及循环读取
获得字符串的长度用len()
利用in和not in可以检查字符串中是否包含某个特定字符
1#访问字符串中特定位置字符
2x="apple"
3print(x[0])#结果为a
4print(x[1])#结果为p
5#循环读取字符串中的字符
6for i in "apple":
7 print(i)
8#结果为a
9#p
10#p
11#l
12#e
13
14#获取字符串的长度
15x="apple"
16print(len(x))#结果为5
17
18#检查字母a是否位于字符串x中
19x="apple"
20print("a" in x)#结果为True
21#检查字母a是否不位于字符x中
22x="apple"
23print("a" not in x)#结果为False -
Python中可以直接利用索引对字符串进行切片,索引从0开始,索引从A到B含头不含尾,如[0,3]是指字符串中第1、2、3个字符。
1a="Hello"
2print(a[0:2])#结果为He
3print(a[3:])#结果为lo
4print(a[-1])#结果为o
5print(a[-4:-2])#结果为el -
Python的字符串操作
1a="Hello a "
2#转换大小写
3print(a.upper())#结果为"HELLO A "
4print(a.lower())#结果为"hello a "
5#去除首尾空白字符
6print(a.strip())#结果为"Hello a"
7#替换字符
8print(a.replace("l","m"))#结果为"Hemmo a"
9#分割字符串
10print(a.split("e"))#以e为分隔符分割字符串,结果为["H","llo a"]
11#连接多个字符串
12x="mm"
13y="nn"
14print(x+y)#结果为"mmnn"
15print(x+" "+y)#结果为"mm nn" -
连接字符串与数字
字符串与数字属于不同类型,无法直接用+连接,可借助format()在字符串中指定{}的位置添加数字
1age=4
2txt="I am"+age+"years old."
3print(txt)#会报错
4txt="I am {} years old."
5print(txt.format(age))#结果为"I am 4 years old"
6x=2
7y=3
8txt="I have {} apples and {} oranges."
9print(txt.format(x,y))#结果为"I have 2 apples and 3 oranges." -
Python中的转义字符
Python字符串中的特殊字符需要插入,特殊字符包括
1print("app'le")#单引号,结果为"app'le"
2print("app"le")#双引号,结果为"app"le"
3print("app\le")#反斜杠,结果为"apple"
4print("appnle")#换行符,结果为"app
5#le"
6print("apprle")#回车键,结果为"app
7#le"
8print("apptle")#tab键,结果为"app le" -
Python中的字符串方法
1#capitalize()设置首字母为大写,其余均为小写
2txt="hello, World!"
3print(txt.capitalize())#结果为Hello,world!
4
5#casefold()将所有字母设置为小写
6txt="Hello, World!"
7print(txt.casefold())#结果为hello, world!
8#upper()将所有字母设为大写
9#lower()将所有字母设为小写
10#swapcase()将大写转为小写,将小写转为大写
11
12#center()生成以指定字符串为中心的特定长度字符串
13txt="apple"
14print(txt.center(20))#默认以空格填补,结果为" apple "
15print(txt.center(20,"X"))#以X填补,结果为"XXXXXXXappleXXXXXXXX"
16
17#ljust()生成特定字符串在左的指定长度的字符串
18txt="apple"
19print(txt.ljust(10))#结果为"apple ",默认以空格填满
20print(txt.ljust(10,"N"))#结果为"appleNNNNN"
21
22#rjust()同上,只不过字符串位于右侧
23
24#count()获取指定字符在某字符串中出现的次数
25txt="apple"
26print(txt.count("p"))#默认对整个字符串进行搜索,结果为2
27print(txt.count("p",0,2))#指定搜索的范围为txt[0,2],结果为1
28
29#endswith()检查字符串末尾的字符
30txt="apple"
31print(txt.endswith("e"))#结果为True
32print(txt.endswith("e",1,3))#指定搜索位置为txt[1,3],结果为False
33
34#find()查找字符串中特定字符第一次出现的位置
35txt="apple"
36print(txt.find("a"))#结果为0
37print(txt.find("p"))#结果为1
38print(txt.find("m"))#结果为-1,如果不存在则返回-1
39print(txt.find("p",0,2))#指定搜索范围为txt[0,2],结果为1
40
41#rfind()与find()类似,返回字符串中特定字符最后一次出现的位置,不存在即返回-1
42
43#index()返回字符串中特定字符第一次出现的位置
44txt = "Hello, welcome to my world."
45print(txt.index("H"))#结果为0
46print(txt.find("q"))#结果为-1
47print(txt.index("q"))#会报错
48
49#rindex()与index()类似,返回字符串中特定字符最后一次出现的位置,不存在会报错
50
51#format()向字符串中插入变量
52txt="My name is {}, i am {} years old."
53print(txt.format("John",24))#结果为"My name is John, i am 24 years old."
54txt="My name is {name}, i am {age} years old."
55print(txt.format(name="John",age=24))#结果为"My name is John, i am 24 years old."
56#{}中可以不填内容,可以填数字的index或者是字符,但字符必须指定
57
58#isalnum()判断某字符串是否只包含字母(a-z)和数字
59txt="apple3"
60a="abc_1"
61print(txt.isalnum())#结果为True
62print(a.isalnum())#结果为False
63#isalpha()判断某字符串是否只包含字母(a-z)
64#isdecimal()判断某字符串是否只包含数字(0-9)
65#isidentifier()判断某字符串是否是identifier,identifier只包含字母a-z、数字0-9、以及下划线,以数字开头或包含空格的字符串不是identifier
66#islower()判断字符串中字母是否都为小写
67#isnumeric()判断字符串中是否只有数字0-9
68#isprintable()判断字符串中的字符是否都可打印,换行符n和回车r为不可打印的字符
69#isspace()判断字符串中的字符是否都为空白符
70#istitle()判断字符串中是否所有单词的首字母都大写,而其余字母小写
71#isupper()判断字符串是否全部大写
72
73#join()将一个字符串作为分隔符加入到一个列表、元祖、字典中,使其连成一个长的字符串
74myTuple = ("John", "Peter", "Vicky")
75x = "#".join(myTuple)
76print(x)#结果为John#Peter#Vicky
77test=["a","b"]
78print("mm".join(test))#结果为ammb
79myDict = {"name": "John", "country": "Norway"}
80mySeparator = "TEST"
81x = mySeparator.join(myDict)
82print(x)#结果为nameTESTcountry,加入字典的话,只会连接字典的Key
83
84#lstrip()从左侧删除字符串中所有指定字符,默认为空格
85txt=" smlmsxxx "
86print(txt.lstrip())#结果为"xxx "
87print(txt.lstrip(" sm"))#结果为"lmsxxx "
88#rstrip()同上,从右侧开始
89#strip()同时,为同时去除左右两端的指定字符,默认为空格
90
91
92#maketrans()替换字符,与translate()搭配使用
93txt = "Hi Sam!"
94x = "mSa"
95y = "eJo"
96mytable = txt.maketrans(x, y)#指定要换的字符
97print(txt.translate(mytable))#结果为"Hi Joe"
98
99txt = "Good night Sam!"
100x = "mSa"
101y = "eJo"
102z = "odnght"
103mytable = txt.maketrans(x, y, z)#x和y为指定要换的字符,z指定要从原字符串中删除的字符
104print(txt.translate(mytable))#结果为"G i Joe"
105
106#partition()将字符串根据指定字符分成三部分(以首次出现为准),并以元祖的形式保存
107txt="apple"
108print(txt.partition("p"))#结果为("a","p","ple")
109
110#rpartition()类似partition()将字符串根据指定字符分成三部分(以最后一次出现为准),并以元祖形式保存
111
112#replace()替换字符串中指定字符
113txt="apple"
114print(txt.replace("p","P"))#结果为aPPle
115print(txt.replace("p","P",1))#结果为aPple,数字指定了替换几个,默认全部替换
116
117#split()将一个字符串根据特定字符分成一个列表,默认为空格
118txt="apple"
119print(txt.split())#结果为["apple"]
120txt="hello world"
121print(txt.split())#结果为["hello","world"]
122print(txt.split("o"))#结果为["hell"," w","rld"]
123print(txt.split("o",1))#结果为["hell"," world"],这里的数字指定分割几次
124
125#rsplit()同上,顺序为从右到左,只有指定分割次数时才会与split()有差别
126txt="hello world"
127print(txt.rsplit())#结果为["hello","world"]
128print(txt.rsplit("o",1))#结果为["hello w","rld"]
129
130#splitlines()根据换行符分割字符串,结果为列表
131txt = "Thank you for the musicnWelcome to the jungle"
132x = txt.splitlines()
133print(x)#结果为['Thank you for the music', 'Welcome to the jungle'],默认舍弃换行符
134x = txt.splitlines(True)
135print(x)#保留换行符,结果为['Thank you for the musicn', 'Welcome to the jungle']
136
137#startwith()判断字符串是否以指定字符开头
138txt="apple"
139print(txt.startswith("ap"))#结果为True
140print(txt.startswith("p"))#结果为False
141
142#title()将字符串转为title格式,即每个单词首字母大写,其余小写
143
144#zfill()在字符串前加0直至达到指定长度
145txt="apple"
146print(txt.zfill(10))#结果为00000apple -
Python中的布尔值
除了False、None、0、””、()、[]、{}为False外,其余均为True
-
Python中的操纵符
算术操作符:加+、减-、乘、除/、取余%、乘方*、除法向下取整数//
赋值操作符:=
比较操作符:等于==、不等于!=、大于>、小于<、大于等于>=、小于等于<=
逻辑操作符:与and、或or、非not
身份操作符:是is、不是is not
关系操作符:在in、不在not in
原文始发于微信公众号(BioInfo):W3Schools-Python基础1
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/238196.html