Python指令汇总(一)

Python指令汇总(一)

一、BIF

BIF即Built-in Functions,意为内置函数。
可输入dir(_ _ builtins _ _)查看Python提供的内置函数列表。

>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

1.help()

用于显示BIF的功能描述

>>> help(print)
Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
    
    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

2.random.randint()

调用random模块,使用randint函数,返回一个随机的整数,可限制取值范围

>>> import random
>>> i = random.randint(1,10)
>>> i
5
>>> i = random.randint(1,10)
>>> i
9

3.类型转换函数

(1) int()

转化为整型

>>> a = '1'
>>> b = int(a)
>>> a,b
('1', 1)
>>> a = 3.1
>>> b = int(a)
>>> a,b
(3.1, 3)

注意浮点型转化为整型是直接将小数部分去掉,不是四舍五入

(2) float()

转化为浮点型

>>> a = '1'
>>> b = float(a)
>>> a,b
('1', 1.0)
>>> a = 1
>>> b = float(a)
>>> a,b
(1, 1.0)

(3) str()

转化为字符串

>>> a = 1
>>> b = str(a)
>>> a,b
(1, '1')
>>> a = 1e5
>>> b = str(a)
>>> a,b
(100000.0, '100000.0')
>>> a = 5.99
>>> b = str(a)
>>> a,b
(5.99, '5.99')

(4) list([iterable])

把一个可迭代对象转换为列表

>>> # 创建一个空列表
>>> a = list()
>>> a
[]
>>> #将字符串中的每个字符迭代存放到列表中
>>> b = list('love')
>>> b
['l', 'o', 'v', 'e']
>>> #将元组中的每个元素迭代存放到列表中
>>> c = list((1,1,2,3,5,6,9,8,7))
>>> c
[1, 1, 2, 3, 5, 6, 9, 8, 7]

(5) tuple([iterable])

把一个可迭代对象转换为元组,用法与list()类似

4.获取变量类型

(1) type()

输入一个变量,返回变量的类型

>>> type('1')
<class 'str'>
>>> type(1)
<class 'int'>
>>> type(1.0)
<class 'float'>
>>> type(1e5)
<class 'float'>
>>> type(True)
<class 'bool'>

(2) isinstance()

输入一个待确定类型的数据,再输入一个数据类型,返回True或False,True表示类型一致,False表示类型不一致

>>> a = '1'
>>> isinstance(a,str)
True
>>> isinstance(1,float)
False
>>> isinstance(1,int)
True

5.常用操作符

(1)算数操作符

+     -     *     /     %     **     // 
+、-、*、/对变量自身进行运算时,可以进行简化,如:
>>> a = b = c = d = 10
>>> a += 1
>>> b -= 3
>>> c *= 5
>>> d /= 2
>>> a,b,c,d
(11, 7, 50, 5.0)

//意为地板除法,即计算结果取比商大的最小整型,也就是舍弃小数

>>> 3 // 2
1
>>> 3.0 // 2
1.0
>>> 3.2 // 1.4
2.0

%表示求余数

>>> 20 % 5
0
>>> 20 % 3
2
>>> 20.5 % 3
2.5
>>> 20.5 % 2.5
0.5

**表示幂运算

>>> 3 ** 2
9
>>> 3.0 ** 2.0
9.0
>>> 3.0 ** 2.1
10.04510856630514
>>> -3 ** 2
-9
>>> 3** -2
0.1111111111111111

(2)比较操作符

< <= > >= == !=
比较操作符根据表达式的真假返回布尔类型的值

>>> 2 < 3
True
>>> 2 <= 3
True
>>> 2 > 3
False
>>> 2 >= 3
False
>>> 2 == 3
False
>>> 2 != 3
True

(3)逻辑操作符

and or not
三者优先级不同:not>and>or

>>> 1 and 3
3
>>> 0 and 3
0
>>> 3 and 1
1
>>> 3 and 0
0
>>> 1 or 3
1
>>> 0 or 3
3
>>> 3 or 1
3
>>> 3 or 0
3
>>> not 0
True
>>> not 3
False

在Python中,以下被视为False:
NONE;False(布尔类型);所有的值为零的数;0(整型);0.0(浮点型);0L(长整型);0.0+0.0j(复数);
“”(空字符串);[](空列表 );()(空元组);{}(空字典)

6.序列常用BIF

(1)len(sub)

返回sub参数的长度

>>> str1 = 'I love you'
>>> len(str1)
10
>>> list1 = [1,2,3,4,5,6,7,8,9,1,2]
>>> len(list1)
11
>>> tuple1 = (1,2,3,4,5,6,7,8,9)
>>> len(tuple1)
9

(2)max()

返回序列或参数集合中的最大值,序列中所有元素类型必须一致

>>> str1
'I love you'
>>> max(str1)
'y'
>>> list1
[1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2]
>>> max(list1)
9
>>> tuple1
(1, 2, 3, 4, 5, 6, 7, 8, 9)
>>> max(tuple1)
9
>>> list2 = [1,5,3,8,6,'a']
>>> max(list2)
Traceback (most recent call last):
  File "<pyshell#56>", line 1, in <module>
    max(list2)
TypeError: '>' not supported between instances of 'str' and 'int'

(3)min()

返回序列或参数集合中的最小值,序列中所有元素类型必须一致

(4)sum(iterable[,start])

返回序列的总和,用法与max()、min()一样,但有一个可选参数start,默认为0,表示从该值开始加起

>>> list1
[1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2]
>>> sum(list1)
48
>>> sum(list1,21)
69

(5)sorted(iterable,key=None,reverse=False)

返回一个排序的列表,与方法sort()不同的是,sorted()返回的是一个新的列表

>>> list1 = [1,596,7,3,85,123]
>>> list2 = list1[:]
>>> list1.sort()
>>> sorted(list2)
[1, 3, 7, 85, 123, 596]
>>> list1
[1, 3, 7, 85, 123, 596]
>>> list2
[1, 596, 7, 3, 85, 123]

(6)reversed(sequence)

返回逆向迭代序列的值。与方法reverse()不同的是,reverse()是列表原地翻转,而reversed()是返回一个翻转后的迭代器对象。如果想将其作为对应种类的序列使用,需要使用转变类型的命令

>>> list1
[1, 3, 7, 85, 123, 596]
>>> reversed(list1)
<list_reverseiterator object at 0x001D3BC8>
>>> for each in reversed(list1):
	print(each,end = ',')

	
596,123,85,7,3,1,

(7)enumerate(iterable)

生成由二元组构成的一个迭代对象,每个二元组由可迭代参数的索引号及其对应的元素组成

>>> str1
'I love you'
>>> for each in enumerate(str1):
	print(each)

	
(0, 'I')
(1, ' ')
(2, 'l')
(3, 'o')
(4, 'v')
(5, 'e')
(6, ' ')
(7, 'y')
(8, 'o')
(9, 'u')

(8)zip(iter1[,iter2[…]])

返回由各个可迭代参数共同组成的元组

>>> list1
[1, 3, 7, 85, 123, 596]
>>> str1
'I love you'
>>> for each in zip(list1,str1):
	print(each)

	
(1, 'I')
(3, ' ')
(7, 'l')
(85, 'o')
(123, 'v')
(596, 'e')

二、分支与循环

1.if语句

if 条件:
	print(1)
else:
	print(0)
if 条件1:
	print(1)
elif 条件2:
	print(2)
else :
	print(3)

条件表达式(三元操作符)

a = x if 条件 else y

if x < y:
	small = x
else:
	small = y

可转化为

small = x if x < y else y

2.断言assert

当assert后面的条件为假时,程序自动崩溃并抛出AssertionError的异常。可以用于测试程序,在程序中置入检查点

>>> assert 3 < 4
>>> assert 3 > 4
Traceback (most recent call last):
  File "<pyshell#78>", line 1, in <module>
    assert 3 > 4
AssertionError

3.while语句

while 条件:
	循环体

4.for语句

计数器循环

>>> str = 'I love you'
>>> for i in str:
	print(i,end = '')

	
I love you

5.range()

range([start,]stop[,step = 1])
共有三个参数,其中用[]括起来的参数表示这一参数可选。step = 1表示第三个参数的默认值是1。。
生成一个从start参数的值开始,到stop参数的值结束的数字序列

>>> for i in range(5):
	print(i)

	
0
1
2
3
4
>>> for i in range(2,9):
	print(i)

	
2
3
4
5
6
7
8
>>> for i in range(2,9,2):
	print(i)

	
2
4
6
8

6.break语句

break语句的作用是终止当前循环,跳出循环体

7.continue语句

continue语句的作用是终止本轮循环并开始下一轮循环(在开始下一轮循环之前,要先测试循环条件)

三、列表、元组与字符串

1.列表

(1)添加元素

append()方法:

向列表末尾添加一个参数

>>> number
[1, 2, 3, 4, 5, 6]
>>> number.append(7)
>>> number
[1, 2, 3, 4, 5, 6, 7]
extend()方法:

向列表末尾添加多个元素(以一个列表的形式)

>>> number
[1, 2, 3, 4, 5, 6]
>>> number.extend([7,8])
>>> number
[1, 2, 3, 4, 5, 6, 7, 8]
insert()方法:

向列表的任意位置插入元素,有两个参数,第一个表示在列表中的位置,第二个参数是要插入的元素

>>> number
[1, 2, 3, 4, 5, 6, 7, 8]
>>> number.insert(1,1.5)
>>> number
[1, 1.5, 2, 3, 4, 5, 6, 7, 8]

(2)获取元素

直接从索引值中获取

>>> number
[1, 1.5, 2, 3, 4, 5, 6, 7, 8]
>>> number[2]
2

(3)删除元素

remove()方法

删除特定元素而不需要知道它的位置

>>> number
[1, 1.5, 2, 3, 4, 5, 6, 7, 8]
>>> number.remove(1.5)
>>> number
[1, 2, 3, 4, 5, 6, 7, 8]
del语句

删除某个位置的元素或删除列表

>>> number
[1, 2, 3, 4, 5, 6, 7, 8]
>>> del number[1]
>>> number
[1, 3, 4, 5, 6, 7, 8]
>>> del number
>>> number
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    number
NameError: name 'number' is not defined
pop()方法

默认弹出列表的最后一个元素。如果加入索引值作为参数后,可以弹出索引值对应的元素

>>> number
[1, 3, 4, 5, 6, 7, 8]
>>> number.pop()
8
>>> number
[1, 3, 4, 5, 6, 7]
>>> number.pop(2)
4
>>> number
[1, 3, 5, 6, 7]

(4)列表分片

>>> number
[1, 2, 3, 4, 5, 6]
>>> number[0:2]
[1, 2]
>>> number[:2]
[1, 2]
>>> number[3:]
[4, 5, 6]
>>> number[:]
[1, 2, 3, 4, 5, 6]

分片时还可加入第三个参数即步长

>>> number[1:4:2]
[2, 4]
>>> number[::2]
[1, 3, 5]
>>> number[::-1]
[6, 5, 4, 3, 2, 1]

(5)常用操作符

> < =

列表可以比较大小,但大小比较是各个元素依次比较

>>> list1 = [123,234]
>>> list2 = [234,123]
>>> list1 < list2
True
+ *

列表可以通过加号(+)与乘号(*)进行拼接与复制

>>> list1 + list2
[123, 234, 234, 123]
>>> list1 *= 5
>>> list1
[123, 234, 123, 234, 123, 234, 123, 234, 123, 234]
in、not in

成员关系操作符,可以测试列表中是否有某元素

>>> 123 in list2
True
>>> 345 not in list2
True
>>> list1
[1, 2, 3, [4, 5], 6]
>>> 4 in list1
False
>>> 4 in list1[3]
True

可以看出,in 和 not in只能判断一个层次的成员关系

(6)其他方法

count()

计算它的参数在列表中出现的次数

>>> list1 = [1,1,2,2,2,3,4,5,5,6,6,6,6]
>>> list1.count(1)
2
>>> list1.count(6)
4
index()

返回它的参数在列表中的位置

>>> list1.index(1)
0

可以看出,返回的是第一个“1”在list1中的位置,还可以加入两个参数用于限定查找的范围,如

>>> start = list1.index(1) + 1
>>> stop = len(list1)
>>> list1.index(1,start,stop)
1
reverse()

将整个列表原地翻转

>>> list1 = [1,2,3,4,5,6,7,8,9]
>>> list1.reverse()
>>> list1
[9, 8, 7, 6, 5, 4, 3, 2, 1]
sort()

用指定方式对列表成员进行排序,默认不需要参数,从小到大排序

>>> list1 = [8,6,4,3,9,7,2,5,1]
>>> list1.sort()
>>> list1
[1, 2, 3, 4, 5, 6, 7, 8, 9]

可以通过修改参数实现从大到小排序

>>> list1 = [8,6,4,3,9,7,2,5,1]
>>> list1.sort(reverse=True)
>>> list1
[9, 8, 7, 6, 5, 4, 3, 2, 1]

2.元组

元组不可改变,创建时一般用()
更新元组需要用分片的方法将元组拆分为两部分,然后再使用连接操作符“+”连同要加入的元素一起合并成一个新元组,再将原来的变量名指向这一新元组。
如果要删除元素也可以用相同的方法,将元组分片后再重新组合。
删除元组可以使用del语句,也可以弃之不管,Python会在元组不再被用到时将其回收。
可以用在元组上的操作符有拼接操作符(+)、重复操作符(*)、关系操作符(< > <= >= !=)、逻辑操作符(and、or、not)、成员关系操作符(in、not in)

3.字符串

(1)大小写转化

capitalize()

把字符串的第一个字符改成大写,其他字符都改成小写

>>> str1 = 'aBcDeFgH'
>>> str1.capitalize()
'Abcdefgh'
casefold()

把整个字符串中的所有字符改成小写

>>> str1 = 'aBcDeFgH'
>>> str1.casefold()
'abcdefgh'
lower()

转换字符串中所有大写字符为小写(仅英文字符)

>>> str1 = 'aBcDeFgH'
>>> str1.lower()
'abcdefgh'
upper()

转换字符串中所有小写字符为大写

>>> str1 = 'aBcDeFgH'
>>> str1.upper()
'ABCDEFGH'
swapcase()

翻转字符串中的大小写

>>> str1 = 'aBcDeFgH'
>>> str1.swapcase()
'AbCdEfGh'
title()

返回标题化(所有单词都是以大写开始,其余字母均小写)的字符串

>>> str1 = 'i love yOU'
>>> str1.title()
'I Love You'

(2)格式调整

center(width,filter=’ ')

返回以原字符串为中心向两边填充的新字符串,填充物为filter,默认为ASCII空格。填充长度为width,若width小于原字符串长度,则返回原字符串副本

>>> str1 = 'aBcDeFgH'
>>> str1.center(10)
' aBcDeFgH '
>>> str1 = 'aBcDeFgH'
>>> str1.center(6)
'aBcDeFgH'
>>> str1 = 'aBcDeFgH'
>>> str1.center(12,'1')
'11aBcDeFgH11'
expandtabs([tabsize=8])

把字符串中的tab符号(\t)转换为空格,如不指定参数,默认空格数是tabsize=8

str1 = 'I love\tyou'
print(str1)
print(str1.expandtabs())
print(str1.expandtabs(0))
print(str1.expandtabs(1))
print(str1.expandtabs(2))
print(str1.expandtabs(3))
print(str1.expandtabs(4))
print(str1.expandtabs(5))
print(str1.expandtabs(6))
print(str1.expandtabs(7))
print(str1.expandtabs(8))
print(str1.expandtabs(9))
print(str1.expandtabs(10))
print(str1.expandtabs(11))

I love	you
I love  you
I loveyou
I love you
I love  you
I love   you
I love  you
I love    you
I love      you
I love you
I love  you
I love   you
I love    you
I love     you
join(sub)

以字符串作为分隔符,插入到sub中所有的字符之间

>>> str1 = 'abcdefgh'
>>> str2 = '1'
>>> str2.join(str1)
'a1b1c1d1e1f1g1h'
ljust(width)

返回一个左对齐的字符串,并使用空格填充长度为width的新字符串

>>> str1
'abcdefgh'
>>> str1.ljust(6)
'abcdefgh'
>>> str1.ljust(10)
'abcdefgh  '
>>> str1.ljust(10,'1')
'abcdefgh11'
lstrip()

去掉字符串左边的所有空格

>>> str1 = '    sfasgsdg    '
>>> str1.lstrip()
'sfasgsdg    '
rjust(width)

返回一个右对齐的字符串,并使用空格填充长度为width的新字符串

>>> str1 = 'abcdefgh'
>>> str1.rjust(6)
'abcdefgh'
>>> str1.rjust(10)
'  abcdefgh'
>>> str1.rjust(10,'1')
'11abcdefgh'
rstrip()

删除字符串末尾的空格

>>> str1 = '    sfasgsdg    '
>>> str1.rstrip()
'    sfasgsdg'
strip([chars])

删除字符串前边和后边所有的空格,chars参数可以定制删除的字符,可选

>>> str1 = '    sfasgsdg    '
>>> str1.strip()
'sfasgsdg'
>>> str1 = '1afsa1vdag1'
>>> str1.strip('1')
'afsa1vdag'
zfill(width)

返回长度为width的字符串,原字符串右对齐,前边用0填充

>>> str1 = 'dagsdgaa'
>>> str1.zfill(6)
'dagsdgaa'
>>> str1.zfill(10)
'00dagsdgaa'

(3)检查字符串

isalnum()

如果字符串至少有一个字符并且所有字符都是字母或数字则返回True,否则返回False

>>> str1 = ''
>>> str2 = 'fa513'
>>> str3 = '   afsaf56'
>>>> str1.isalnum()
False
>>> str2.isalnum()
True
>>> str3.isalnum()
False
isalpha()

如果字符串至少有一个字符并且所有字符都是字母则返回True,否则返回False。为防止将不同系列中的相同的字符都判断为字母,可以先将数据encode成utf-8的形式再进行判断

>>> 'A'.isalpha()
True
>>> 'A'.encode(encoding='utf-8').isalpha()
True
>>> 'Α'.isalpha()
True
>>> 'Α'.encode(encoding='utf-8').isalpha()
False
>>> 'А'.isalpha()
True
>>> 'А'.encode(encoding='utf-8').isalpha()
False

第一个“A”为英文字母,第二个和第三个分别为希腊字母与俄文字母

isdecimal()、isdigit()、isnumeric()

都用于判断字符串中是否包含数字,区别如下:
isdecimal:是否为十进制数字符,包括Unicode数字、双字节全角数字,不包括罗马数字、汉字数字、小数;
isdigit:是否为数字字符,包括Unicode数字,单字节数字,双字节全角数字,不包括汉字数字,罗马数字、小数
isnumeric:是否所有字符均为数值字符,包括Unicode数字、双字节全角数字、罗马数字、汉字数字,不包括小数。

>>> def isnumber(s):
	print(s+'isdigit: ',s.isdigit())
	print(s+'isdecimal: ',s.isdecimal())
	print(s+'isnumeric: ',s.isnumeric())

>>> isnumber('123')
123isdigit:  True
123isdecimal:  True
123isnumeric:  True
>>> isnumber('123.0')
123.0isdigit:  False
123.0isdecimal:  False
123.0isnumeric:  False
>>> isnumber('一二三')
一二三isdigit:  False
一二三isdecimal:  False
一二三isnumeric:  True
>>> isnumber('壹贰叁')
壹贰叁isdigit:  False
壹贰叁isdecimal:  False
壹贰叁isnumeric:  True
>>> isnumber('ⅠⅡⅢ')
ⅠⅡⅢisdigit:  False
ⅠⅡⅢisdecimal:  False
ⅠⅡⅢisnumeric:  True
islower()

如果字符串中至少包含一个区分大小写的字符,并且这些字符都是小写,则返回True,否则返回False

isupper()

如果字符串中至少包含一个区分大小写的字符,并且这些字符都是小写,则返回True,否则返回False

isspace()

如果字符串中只包含空格,则返回True,否则返回False

istitle()

如果字符串是标题化(所有的单词都是以大写开始,其余字母均小写),则返回True,否则返回False

endwith(sub[,start[,end]])

检查字符串是否以sub子字符串结束,如果是,返回True,否则返回False。start和end参数表示范围,可选
sub不仅可以是一个字符串,也可以由多个字符串组成的元组,只要满足其中一个就返回True

>>> 'I Love You'.endswith('You')
True
>>> 'I Love You'.endswith(('You','Him','Her','Me'))
True
find(sub[,start[,end]])

检查sub是否包含在字符串中,如果有则返回索引值,否则返回-1,start和end参数表示范围,可选

>>>'Hello world'.find('o')
4
>>> 'Hello world'.find('i')
-1
index(sub[,start[,end]])

跟find方法一样,不过如果sub不在字符串中会产生异常

>>> 'Hello world'.index('o')
4
>>> 'Hello world'.index('i')
Traceback (most recent call last):
  File "<pyshell#28>", line 1, in <module>
    'Hello world'.index('i')
ValueError: substring not found
rfind(sub[,start[,end]])

类似于find()方法,不过是从右边开始查找

>>> 'Hello world'.rfind('o')
7
>>> 'Hello world'.rfind('i')
-1
rindex(sub[,start[,end]])

类似于index()方法,不过是从右边开始查找

>>> 'Hello world'.rindex('o')
7
>>> 'Hello world'.rindex('i')
Traceback (most recent call last):
  File "<pyshell#32>", line 1, in <module>
    'Hello world'.rindex('i')
ValueError: substring not found
startwith(prefix[,start[,end]])

检查字符串是否以prefix子字符串开头,如果是,返回True,否则返回False。start和end参数表示范围,可选
prefix不仅可以是一个字符串,也可以由多个字符串组成的元组,只要满足其中一个就返回True

>>> 'I Love You'.startswith('I')
True
>>> 'I Love You'.startswith(('I','You','He','She'))
True

(4)其他

count(sub[,start[,end]])

返回sub在字符串里边出现的次数,start和end参数表示范围,可选

>>> 'Hello world'.count('l')
3
>>> 'Hello world'.count('i')
0
encode(encoding=‘utf-8’,errors=‘strict’)

以encoding指定的编码格式对字符串进行编码
基本的编码类型有ASCII编码(英文)、GB2312编码(中文)、Unicode编码(各语言统一)、Utf-8编码(由Unicode转化而来)等

partition(sub)

找到子字符串sub,把字符串分成一个3元组(pre_sub,sub,fol_sub),如果字符串不包含sub则返回(‘原字符串’,’ ‘,’ ')

>>> 'I Love You'.partition(' ')
('I', ' ', 'Love You')
>>> 'I Love You'.partition('p')
('I Love You', '', '')
rpartition(sub)

类似于partition()方法,不过是从右边开始查找

>>> 'I Love You'.rpartition(' ')
('I Love', ' ', 'You')
>>> 'I Love You'.rpartition('p')
('', '', 'I Love You')
replace(old,new[,count])

把字符串中的old子字符串替换成new子字符串,如果count指定,则替换不超过count次

>>> 'Hello world'.replace('l','i')
'Heiio worid'
>>> 'Hello world'.replace('l','i',2)
'Heiio world'
split(sep=None,maxsplit=-1)

不带参数默认是以空格为分隔符切片字符串,如果maxsplit参数有设置,则仅分隔maxsplit个字符串,返回切片后的字符串拼接的列表

str1 = 'https://blog.csdn.net/mozheng_zy/article/details/10406479'
print('0:%s'%str1.split('/'))
print('1:%s'%str1.split('/')[0])
print('2:%s'%str1.split('/')[6])
print('3:%s'%str1.split('/')[-1])
print('4:%s'%str1.split('/')[-7])
print('5:%s'%str1.split('/',-1))
print('6:%s'%str1.split('/',0))
print('7:%s'%str1.split('/',1))
print('8:%s'%str1.split('/',2))
print('9:%s'%str1.split('/',3))
print('10:%s'%str1.split('/',4))
print('11:%s'%str1.split('/',5))
print('12:%s'%str1.split('/',6))
print('13:%s'%str1.split('/',7))
print('14:%s'%str1.split('/',8))
print('15:%s'%str1.split('/',9))

0:['https:', '', 'blog.csdn.net', 'mozheng_zy', 'article', 'details', '10406479']
1:https:
2:10406479
3:10406479
4:https:
5:['https:', '', 'blog.csdn.net', 'mozheng_zy', 'article', 'details', '10406479']
6:['https://blog.csdn.net/mozheng_zy/article/details/10406479']
7:['https:', '/blog.csdn.net/mozheng_zy/article/details/10406479']
8:['https:', '', 'blog.csdn.net/mozheng_zy/article/details/10406479']
9:['https:', '', 'blog.csdn.net', 'mozheng_zy/article/details/10406479']
10:['https:', '', 'blog.csdn.net', 'mozheng_zy', 'article/details/10406479']
11:['https:', '', 'blog.csdn.net', 'mozheng_zy', 'article', 'details/10406479']
12:['https:', '', 'blog.csdn.net', 'mozheng_zy', 'article', 'details', '10406479']
13:['https:', '', 'blog.csdn.net', 'mozheng_zy', 'article', 'details', '10406479']
14:['https:', '', 'blog.csdn.net', 'mozheng_zy', 'article', 'details', '10406479']
15:['https:', '', 'blog.csdn.net', 'mozheng_zy', 'article', 'details', '10406479']
splitlines(([keepends=False]))

按照’\n’、’\r’或‘\r\n’分隔,返回一个包含各行作为元素的列表,默认不包含换行符,若keepends=True,则包含换行符

str = '''从明天起,做一个幸福的人
喂马、劈柴,周游世界
从明天起,关心粮食和蔬菜
我有一所房子,面朝大海,春暖花开

从明天起,和每一个亲人通信
告诉他们我的幸福
那幸福的闪电告诉我的
我将告诉每一个人

给每一条河每一座山取一个温暖的名字
陌生人,我也为你祝福
愿你有一个灿烂的前程
愿你有情人终成眷属
愿你在尘世获得幸福
我只愿面朝大海,春暖花开'''
print(str.splitlines())
print(str.splitlines(True))
['从明天起,做一个幸福的人', '喂马、劈柴,周游世界', '从明天起,关心粮食和蔬菜', '我有一所房子,面朝大海,春暖花开', '', '从明天起,和每一个亲人通信', '告诉他们我的幸福', '那幸福的闪电告诉我的', '我将告诉每一个人', '', '给每一条河每一座山取一个温暖的名字', '陌生人,我也为你祝福', '愿你有一个灿烂的前程', '愿你有情人终成眷属', '愿你在尘世获得幸福', '我只愿面朝大海,春暖花开']
['从明天起,做一个幸福的人\n', '喂马、劈柴,周游世界\n', '从明天起,关心粮食和蔬菜\n', '我有一所房子,面朝大海,春暖花开\n', '\n', '从明天起,和每一个亲人通信\n', '告诉他们我的幸福\n', '那幸福的闪电告诉我的\n', '我将告诉每一个人\n', '\n', '给每一条河每一座山取一个温暖的名字\n', '陌生人,我也为你祝福\n', '愿你有一个灿烂的前程\n', '愿你有情人终成眷属\n', '愿你在尘世获得幸福\n', '我只愿面朝大海,春暖花开']

split与splitlines的区别:

>>> print('hello\n'.splitlines(),'hello\n'.split('\n'))
['hello'] ['hello', '']
translate(table)

根据table的规则(可以由str.maketrans(‘a’,‘b’)定制)转换字符串中的字符

(5)格式化

format()

format()方法接受位置参数与关键字参数
位置参数:

>>> '{0} love {1}{2}'.format('I','you','!')
'I love you!'

关键字参数:

>>> '{a} love {b}{c}'.format(a='I',b='you',c='!')
'I love you!'

如果要将位置参数与关键字参数结合使用,必须把位置参数放在关键字参数之前,否则会出错:

>>> '{0} love {b}{c}'.format('I',b='you',c='!')
'I love you!'
>>> '{a} love {b}{0}'.format(a='I',b='you','!')
SyntaxError: positional argument follows keyword argument

在格式化中,如果想让最终的结果显示{},可以在它外面再包一层{}:

>>> '{{0}}'.format('123')
'{0}'

特殊功能:

>>> '{0:.2f}'.format(3.14159)
'3.14'

“:”表示格式化符号的开始,“.2”表示四舍五入保留两位小数点,f表示定点数

格式化操作符:%
符号含义
%c格式化字符及其ASCII码
%s格式化字符串
%d格式化整数
%o格式化无符号八进制数
%x格式化无符号十六进制数
%X格式化无符号十六进制数(大写)
%f格式化浮点数,可指定小数点后的精度
%e用科学计数法格式化浮点数
%E作用同%e,用科学计数法格式化浮点数
%g根据值的大小决定用%f或%e
%G作用同%g,根据值的大小决定使用%f或%E
>>> '%c'%33
'!'
>>> '%c'%103
'g'
>>> '%d转化为八进制是:%o'%(234,234)
'234转化为八进制是:352'
>>> '%d转化为十六进制是:%x'%(234,234)
'234转化为十六进制是:ea'
>>> '%f'%123456
'123456.000000'
>>> '%.1f'%123456
'123456.0'
>>> '%e'%123456
'1.234560e+05'
>>> '%E'%123456
'1.234560E+05'
>>> '%g'%123456
'123456'
>>> '%g'%51686262843512689365
'5.16863e+19'
>>> '%g'%1.265955995296
'1.26596'

辅助指令

符号含义
m.nm是显示的最小总宽度,n是小数点后的位数
-结果左对齐
+在正数前面显示加号(+)
#在八进制前面显示‘0o’,在十六进制前面显示‘0x’或’0X’
0显示的数字前面填充‘0’代替空格
>>> '%6.2f'%3.14159
'  3.14'
>>> '%06.2f'%3.14159
'003.14'
>>> '%-6.2f'%3.14159
'3.14  '
>>> '%-06.2f'%3.14159
'3.14  '
>>> '%-+6.2f'%3.14159
'+3.14 '
>>> '%#o'%123
'0o173'
>>> '%#x'%123
'0x7b'
>>> '%#X'%123
'0X7B'

4.部分转义字符

符号说明
\’单引号
\"双引号
\a发出系统响铃声
\b退格符
\n换行符
\t横向制表符(TAB)
\v纵向制表符
\r回车符
\f换页符
\o八进制数代表的字符
\x十六进制数代表的字符
\0表示一个空字符
\反斜杠

在学习《小甲鱼零基础学习python》过程中总结而来,仅供个人参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值