python3学习总结(个人遇到问题后搞明白的知识点总结)

strip()方法

描述: Python strip() 方法用于移除字符串头尾指定的字符(默认为空格)或字符序列。

   注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。

语法: strip()方法语法:    str.strip([chars]);

参数 :chars -- 移除字符串头尾指定的字符序列。

返回值 :返回移除字符串头尾指定的字符序列生成的新字符串。

实例

以下实例展示了 strip() 函数的使用方法:

#!/usr/bin/python3
 
str = "*****this is **string** example....wow!!!*****"
print (str.strip( '*' ))  # 指定字符串 *

输出:
 this is **string** example....wow!!!

从结果上看,可以注意到中间部分的字符并未删除。

以上下例演示了只要头尾包含有指定字符序列中的字符就删除:

#!/usr/bin/python3
 
str = "123abcrunoob321"
print (str.strip( '12' ))  # 字符序列为 12

输出为:3abcrunoob3

总结: 

1、strip() 处理的时候,如果不带参数,默认是清除两边的空白符,例如:/n, /r, /t, ' ')。

2、strip() 带有参数的时候,这个参数可以理解一个要删除的字符的列表,是否会删除的前提是从字符串最开头和最结尾是不是包含要删除的字符,如果有就会继续处理,没有的话是不会删除中间的字符的。

addr = '[email protected]'
addr1 = addr.strip('12')

以上例子因为 1 在 [email protected] 的左边第一个,所以删除了继续判断,2 也存在,所以也删除。结果为:

[email protected]

如果要删除的字符列表不包含第一个字符呢?

addr = '[email protected]'addr1 = addr.strip('23')

此时 2 不是第一个字符,所以无法继续,结果为:

[email protected]

split()方法 

描述:split()通过指定分隔符对字符串进行切片,如果参数num 有指定值,则仅分隔 num 个子字符串

split()方法语法:               

                                   str.split(str="", num=string.count(str))

参数

  • str -- 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。

  • num -- 分割次数。

返回值:           返回分割后的字符串列表。

实例

以下实例展示了split()函数的使用方法:

#!/usr/bin/python3

str = "this is string example....wow!!!"
print (str.split( ))
print (str.split('i',1))
print (str.split('w'))


输出:
    ['this', 'is', 'string', 'example....wow!!!']
    ['th', 's is string example....wow!!!']
    ['this is string example....', 'o', '!!!']

 总结 :当出现file.strip().split()时,如果file不是字符串类型,则strip默认只会删除前后空白,但并不会把文件转换为字符串,

而split()不仅默认按照空白进行切片,同时还把数据转换成字符串类型,例如:

# 只使用strip()

fr = open('testSet.txt')
for line in fr.readlines():
    print('line : ', line)
    lines = line.strip()
    print('lines: ', lines)
    print('-----------------------')
    
    
    
line :  -0.017612	14.053064	0
lines:  -0.017612	14.053064	0
-----------------------
line :  -1.395634	4.662541	1
lines:  -1.395634	4.662541	1
-----------------------
line :  -0.752157	6.538620	0
lines:  -0.752157	6.538620	0
-----------------------

 # 只使用split()

fr = open('testSet.txt')
for line in fr.readlines():
    print('line : ', line)
    lines = line.split()
    print('lines: ', lines)
    print('-----------------------')
    
line :  -0.017612	14.053064	0
lines:  ['-0.017612', '14.053064', '0']
-----------------------
line :  -1.395634	4.662541	1
lines:  ['-1.395634', '4.662541', '1']
-----------------------
line :  -0.752157	6.538620	0
lines:  ['-0.752157', '6.538620', '0']
-----------------------

二者联合使用

fr = open('testSet.txt')
for line in fr.readlines():
    print('line : ', line)
    lines = line.strip().split()
    print('lines: ', lines)
    print('-----------------------')
    
line :  -0.017612	14.053064	0
lines:  ['-0.017612', '14.053064', '0']
-----------------------
line :  -1.395634	4.662541	1
lines:  ['-1.395634', '4.662541', '1']
-----------------------
line :  -0.752157	6.538620	0
lines:  ['-0.752157', '6.538620', '0']
-----------------------
line :  -1.322371	7.152853	0
lines:  ['-1.322371', '7.152853', '0']
-----------------------
line :  0.423363	11.054677	0
lines:  ['0.423363', '11.054677', '0']
-----------------------

List append() 和 extent()方法

描述

     append() 方法用于在列表末尾添加新的对象。

     extend() 函数用于在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)

语法

append()方法语法:

  list.append(obj)

      list.extend(seq)

参数

  •  obj -- 添加到列表末尾的对象。
  • seq -- 元素列表

返回值

append  该方法无返回值,但是会修改原来的列表。

extend  该方法没有返回值,但会在已存在的列表中添加新的列表内容。

示例:

def changeextend(str):
    "print string with extend"
    mylist.extend([40,50,60]);
    print ("print string mylist:",mylist)
    return
def changeappend(str):
    "print string with append" 
    mylist.append( [7,8,9] )
    print("print string mylist:",mylist )
    return
mylist = [10,20,30]
changeextend( mylist );
print ("print extend mylist:", mylist )
changeappend( mylist );
print ("print append mylist:", mylist )
print string mylist: [10, 20, 30, 40, 50, 60]
print extend mylist: [10, 20, 30, 40, 50, 60]
print string mylist: [10, 20, 30, 40, 50, 60, [7, 8, 9]]
print append mylist: [10, 20, 30, 40, 50, 60, [7, 8, 9]]

readline() 和readlines()方法

概述

readline() 方法用于从文件读取整行,包括 "\n" 字符。如果指定了一个非负数的参数,则返回指定大小的字节数,包括 "\n" 字符。

readlines() 方法用于读取所有行(直到结束符 EOF)并返回列表,该列表可以由 Python 的 for... in ... 结构进行处理。 如果碰到结束符 EOF 则返回空字符串。

如果碰到结束符 EOF 则返回空字符串。

语法

readline() 方法语法如下:

fileObject.readline(); 
fileObject.readlines( );

参数

  • readline ()      size -- 从文件中读取的字节数。

  • readlines() 无

返回值

readline 返回从字符串中读取的字节。

readlines 返回列表,包含所有的行。

实例

以下实例演示了 readline() 方法的使用:

文件 runoob.txt 的内容如下:

1:www.runoob.com
2:www.runoob.com
3:www.runoob.com
4:www.runoob.com
5:www.runoob.com

循环读取文件的内容:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 打开文件
fo = open("runoob.txt", "r+")
print ("文件名为: ", fo.name)

line = fo.readline()
print ("读取第一行 %s" % (line))

line = fo.readline(5)
print ("读取的字符串为: %s" % (line))

# 关闭文件
fo.close()

以上实例输出结果为:

文件名为:  runoob.txt
读取第一行 1:www.runoob.com

读取的字符串为: 2:www

readlines示例:

# 打开文件
fo = open("runoob.txt", "r")
print ("文件名为: ", fo.name)
 
for line in fo.readlines():                          #依次读取每行  
    line = line.strip()                             #去掉每行头尾空白  
    print ("读取的数据为: %s" % (line))
 
# 关闭文件
fo.close()
文件名为:  runoob.txt
读取的数据为: 1:www.runoob.com
读取的数据为: 2:www.runoob.com
读取的数据为: 3:www.runoob.com
读取的数据为: 4:www.runoob.com
读取的数据为: 5:www.runoob.com

format 格式化函数 

Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。

基本语法是通过 {} 和 : 来代替以前的 % 。

format 函数可以接受不限个参数,位置可以不按顺序

实例
>>>"{} {}".format("hello", "world")    # 不设置指定位置,按默认顺序
'hello world'
 
>>> "{0} {1}".format("hello", "world")  # 设置指定位置
'hello world'
 
>>> "{1} {0} {1}".format("hello", "world")  # 设置指定位置
'world hello world'

也可以设置参数:

实例
#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
print("网站名:{name}, 地址 {url}".format(name="菜鸟教程", url="www.runoob.com"))
 
# 通过字典设置参数
site = {"name": "菜鸟教程", "url": "www.runoob.com"}
print("网站名:{name}, 地址 {url}".format(**site))
 
# 通过列表索引设置参数
my_list = ['菜鸟教程', 'www.runoob.com']
print("网站名:{0[0]}, 地址 {0[1]}".format(my_list))  # "0" 是必须的


输出:

网站名:菜鸟教程, 地址 www.runoob.com
网站名:菜鸟教程, 地址 www.runoob.com
网站名:菜鸟教程, 地址 www.runoob.com

 字符串% 操作符,格式如下:

% 操作符,格式如下:

%[(name)][flags][width].[precision]typecode
 (name) 为命名
 flags 可以有 +,-,' '或 0。+ 表示右对齐。- 表示左对齐。' ' 为一个空格,表示在正数的左侧填充一个空格,从而与负数对齐。0 表示使用 0 填充。
 width 表示显示宽度
 precision 表示小数点后精度
以下是类型码:

%s    字符串 (采用str()的显示)
%r    字符串 (采用repr()的显示)
%c    单个字符
%b    二进制整数
%d    十进制整数
%i    十进制整数
%o    八进制整数
%x    十六进制整数
%e    指数 (基底写为e)
%E    指数 (基底写为E)
%f    浮点数
%F    浮点数,与上相同%g    指数(e)或浮点数 (根据显示长度)
%G    指数(E)或浮点数 (根据显示长度)
%%    字符"%"
举例

>>> print("%6.3f" % 2.3)
 2.300
 第一个 % 后面的内容为显示的格式说明,6 为显示宽度,3 为小数点位数,f 为浮点数类型
 第二个 % 后面为显示的内容来源,输出结果右对齐,2.300 长度为 5,故前面有一空格
>>> print("%+10x" % 10)
    +a
x 为表示 16 进制,显示宽度为 10,前面有 8 个空格。

>>>print("%-5x" % -10)
-a  
%-5x 负号为左对齐,显示宽度为 5,故 -a 后面有 3 个空格

>>>pi=3.1415
>>>print ("pi的值是%s"%pi)
pi的值是3.1415

>>>print ("pi的值是%.8f"%pi)
pi的值是3.14150000
上面的 width, precision 为两个整数。我们可以利用 *,来动态代入这两个量。比如:

>>> print("%10.*f" % (4, 1.2))
  1.2000
以下是补充

简单的说,这是一种将其他变量置入字符串特定位置以生成新字符串的操作,比如说:

>>> n = "Runoob"
>>> "My name is %s" % n
'My name is Runoob'
这段代码首先定义了一个名为 n 的变量,内容为 Runoob。然后下方的字符串中有一个 %s,他的含义是“这里将被替换成一个新的字符串”,用作替换的内容放在字符串后面的%后面,就是那个 n。所以最终这个字符串会变成 My name is Runoob。

enumerate() 函数

描述

enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。

语法

以下是 enumerate() 方法的语法:

enumerate(sequence, [start=0])

参数

  • sequence -- 一个序列、迭代器或其他支持迭代对象。
  • start -- 下标起始位置。

返回值

返回 enumerate(枚举) 对象。


实例

以下展示了使用 enumerate() 方法的实例:

>>>seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>>list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>>list(enumerate(seasons, start=1))       # 小标从 1 开始
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]



普通的 for 循环
>>>i = 0
>>>seq = ['one', 'two', 'three']
>>>for element in seq:
...    print(i, seq[i])
...    i += 1
... 
0 one
1 two
2 three


for 循环使用 enumerate
>>>seq = ['one', 'two', 'three']
>>>for i, element in enumerate(seq):
...    print(i, seq[i])
... 
0 one
1 two
2 three
>>>

 map() 函数

描述

map() 会根据提供的函数对指定序列做映射。

第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。

语法

map() 函数语法:

map(function, iterable, ...)

参数

  • function -- 函数
  • iterable -- 一个或多个序列

返回值

Python 2.x 返回列表。

Python 3.x 返回迭代器。

实例

以下实例展示了 map() 的使用方法:

>>>def square(x) :            # 计算平方数
...     return x ** 2
... 
>>> map(square, [1,2,3,4,5])   # 计算列表各个元素的平方
[1, 4, 9, 16, 25]
>>> map(lambda x: x ** 2, [1, 2, 3, 4, 5])  # 使用 lambda 匿名函数
[1, 4, 9, 16, 25]
 
# 提供了两个列表,对相同位置的列表数据进行相加
>>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
[3, 7, 11, 15, 19]

 zip() 函数

描述

zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象,这样做的好处是节约了不少的内存。

我们可以使用 list() 转换来输出列表。

如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。

zip 方法在 Python 2 和 Python 3 中的不同:在 Python 2.x zip() 返回的是一个列表。

语法

zip 语法:

zip([iterable, ...])

参数说明:

  • iterabl -- 一个或多个迭代器;

返回值

返回一个对象。

实例

以下实例展示了 zip 的使用方法:

>>>a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b)     # 返回一个对象
>>> zipped
<zip object at 0x103abc288>
>>> list(zipped)  # list() 转换为列表
[(1, 4), (2, 5), (3, 6)]
>>> list(zip(a,c))              # 元素个数与最短的列表一致
[(1, 4), (2, 5), (3, 6)]
 
>>> a1, a2 = zip(*zip(a,b))          # 与 zip 相反,zip(*) 可理解为解压,返回二维矩阵式
>>> list(a1)
[1, 2, 3]
>>> list(a2)
[4, 5, 6]
>>>

字典 setdefault() 方法

描述
Python 字典 setdefault() 方法和get()方法类似, 如果键不已经存在于字典中,将会添加键并将值设为默认值。

语法
setdefault()方法语法:

dict.setdefault(key, default=None) 


参数
key -- 查找的键值。
default -- 键不存在时,设置的默认键值。


返回值
如果 key 在 字典中,返回对应的值。如果不在字典中,则插入 key 及设置的默认值 default,并返回 default ,default 默认值为 None。

实例
以下实例展示了 setdefault() 方法的使用方法:

#!/usr/bin/python3

dict = {'Name': 'Runoob', 'Age': 7}

print ("Age 键的值为 : %s" %  dict.setdefault('Age', None))
print ("Sex 键的值为 : %s" %  dict.setdefault('Sex', None))
print ("新字典为:", dict)



以上实例输出结果为:

Age 键的值为 : 7
Sex 键的值为 : None
新字典为: {'Age': 7, 'Name': 'Runoob', 'Sex': None}

猜你喜欢

转载自blog.csdn.net/weixin_42398658/article/details/82931637