python基础学习(第一天)
- str, repr, r
>>> print(repr("Hello,\nworld!"))
'Hello,\nworld!'
>>> print(str("Hello,\nworld!"))
Hello,
world!
str将值转化为用户看懂的字符串,repr用以表示表达式的值。
>>> print(r"hello,\n world")
hello,\n world
>>> print(r"hello,world\")
File "<stdin>", line 1
print(r"hello,world\")
^
SyntaxError: EOL while scanning string literal
>>> print(r"hello\
... world")
hello\
world
r表示原始字符串,原始字符串打印,但是末尾能不能是转义符。
- python终端清屏
>>> import os
>>> os.system("cls")
- 数字表示
>>> round(5/6)
1
>>> 5/6
0.8333333333333334
>>> int(5/6)
0
>>> math.floor(5/7)
0
>>> math.ceil(5/7)
1
- 序列
索引
>>> str1=["hhhh",6,7,9]
>>> print(str1[0])
hhhh
>>>print(str1[-1])#倒数
9
切片
>>> ints=[1,2,3,4,5,6,7,8,9,10]
>>> ints[0:4]
[1, 2, 3, 4]
>>> ints[:4]
[1, 2, 3, 4]
>>> ints[-3:-1]
[8, 9]
>>> ints[-3:0]
[]
>>> ints[-3:]
[8, 9, 10]
#显示声明步长
>>> ints[0:4:1]
[1, 2, 3, 4]
>>> ints[0:4:2]
[1, 3]
>>> ints[::3]
[1, 4, 7, 10]
运算
ints1=[1,2,3]
>>> ints1+ints
[1, 2, 3, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> str1=["hhh","hh"]
>>> str1+ints
['hhh', 'hh', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> ints+"hhh"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "str") to list
>>> ints*3
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> sequence = [None] * 10
>>> sequence
[None, None, None, None, None, None, None, None, None, None]
>>> 11 in ints
False
>>> 5 in ints
True #注意大小写
>>> len(ints)
10
>>> max(ints)
10
>>> min(ints)
1
- List
>>> list("hhhh")
['h', 'h', 'h', 'h']
>>> list1=list("hhhgggg")
>>> list1
['h', 'h', 'h', 'g', 'g', 'g', 'g']
>>> list2="".join(list1)
>>> list2
'hhhgggg'
>>> del list1[3]
>>> list1
['h', 'h', 'h', 'g', 'g', 'g']
#切片替换
>>> list1[0:2]=list("dfd")
>>> list1
['d', 'f', 'd', 'h', 'g', 'g', 'g']
- 列表方法
复制、引用
>>> list2=list1
>>> list2[0]="w"
>>> list1
['w', 'f', 'd', 'h', 'g', 'g', 'g']
>>> list2[0]="hhh"
>>> list1
['hhh', 'f', 'd', 'h', 'g', 'g', 'g']
>>> list3=list1.copy()
>>> list3[0]="ggg"
>>> list1
['hhh', 'f', 'd', 'h', 'g', 'g', 'g']
extend()
>>> list1.extend(list2)
>>> list1
['hhh', 'f', 'd', 'h', 'g', 'g', 'g', 'hhh', 'f', 'd', 'h', 'g', 'g', 'g']
sort(), sorted(para)
>>> list1.sort()
>>> list1
['d', 'd', 'f', 'f', 'g', 'g', 'g', 'g', 'g', 'g', 'h', 'h', 'hhh', 'hhh']
>>> list2=list1.sort()
>>> list2
>>> list2=sorted(list1)
>>> list2
['d', 'd', 'f', 'f', 'g', 'g', 'g', 'g', 'g', 'g', 'h', 'h', 'hhh', 'hhh']
>>> list1=["h","hhh","gg","","dhgjd"]
>>> list1.sort(key=len)#函数对象len
>>> list1
['', 'h', 'gg', 'hhh', 'dhgjd']
>>> list1.sort(key=len,reverse=True)
>>> list1
['dhgjd', 'hhh', 'gg', 'h', '']