python 学习第四天 列表、元组和字符串

7 列表

简单的数据类型:
1.整型
2.浮点型
3.布尔型

容器数据类型:
1.列表
2.元组
3.字典
4.集合
5.字符串

7.1列表的定义

列表是有序集合,没有固定的大小,能够保存任意数量的任意类型的python的对象,语法[元素1,元素2,… ,元素n]
关键点是中括号[]和里面的逗号,

7.2列表的创建

1.创建一个普通列表

x = ['Monday','Tuesday','Wednessday','Thursday','Friday']
print(x,type(x))
x = [2,3,4,5,6,7]
print(x,type(x))

2.利用range()创建列表

x = list(range(10))
print(x,type(x))
y = tuple(range(10))
print(y,type(y))
z = list(range(1,11,2))
print(z,type(z))
u = list(range(10,1,-2))
print(u,type(u))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] <class 'list'>
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) <class 'tuple'>
[1, 3, 5, 7, 9] <class 'list'>
[10, 8, 6, 4, 2] <class 'list'>

3.利用推导式创建列表

x = [0] *5
print(x,type(x))

x = [0 for i in range(5)]
print(x,type(x))

x = [i for i in range(10)]
print(x,type(x))

x = [i for i in range(1,10,2)]
print(x,type(x))

x = [i for i in range(10,1,-2)]
print(x,type(x))

x = [i **2 for i in range(1,10)]
print(x,type(x))

x = [i for i in range(100) if (i%2) !=0 and (i%3) ==0]
[0, 0, 0, 0, 0] <class 'list'>
[0, 0, 0, 0, 0] <class 'list'>
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] <class 'list'>
[1, 3, 5, 7, 9] <class 'list'>
[10, 8, 6, 4, 2] <class 'list'>
[1, 4, 9, 16, 25, 36, 49, 64, 81] <class 'list'>

4.创建一个4x3的二维数组

x = [[1,2,3],[4,5,6],[7,8,9],[0,0,0,]]
print(x,type(x))

for i in x:
    print(i,type(x))
    
x = [[0 for col in range(3)] for row in range(4)]
print(x,type(x))

x[0][0] = 1
print(x,type(x))

x = [[0] * 3 for row in range(4)]
print(x,type(x))

x[1][1] = 1
print(x,type(x))
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [0, 0, 0]] <class 'list'>
[1, 2, 3] <class 'list'>
[4, 5, 6] <class 'list'>
[7, 8, 9] <class 'list'>
[0, 0, 0] <class 'list'>
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] <class 'list'>
[[1, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] <class 'list'>
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] <class 'list'>
[[0, 0, 0], [0, 1, 0], [0, 0, 0], [0, 0, 0]] <class 'list'>

注意:由于list的元素可以使任何对象,因此列表所保存的是对象的指针。及时保存一个简单的[1,2,3],也有三个对象和三个指针。
x = [a] * 4操作中,只是创建4个指向list的引用,所以一旦a改变,x中的4个a也会随之改变。

z = [[0]*3]*4
print(z,type(x))

z[0][0]  =1
print(z,type(z))

a = [0] *3
x = [a] * 4
print(x,type(x))

x[0][0] = 1
print(x,type(x))
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] <class 'list'>
[[1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0]] <class 'list'>
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] <class 'list'>
[[1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0]] <class 'list'>

5.创建一个混合列表及空列表
列表的元素可以更改,元组的元素不可更改,因此附加append,extend,插入insert,删除remove,pop。这些方法均可用在他身上。

7.3 向列表中添加元素

1.list.append(obj)在列表末尾添加新的对象,只接受一个参数,参数可以使任何数据类型,被追加的元素在list中保持原来结构类型。

x = ['Monday','Tuesday','Wednessday','Thursday','Friday']
x.append('Thursday')
print(x)
print(len(x))

['Monday', 'Tuesday', 'Wednessday', 'Thursday', 'Friday', 'Thursday']
6

如果追加的元素是一个list,那么这个list将作为一个整体进行追加,注意append()和extend()的区别。

x = ['Monday','Tuesday','Wednessday','Thursday','Friday']
x.append(['Thursday','Sunny'])
print(x)
print(len(x))

['Monday', 'Tuesday', 'Wednessday', 'Thursday', 'Friday', ['Thursday', 'Sunny']]
6

2.list.extend(seq)在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)。
严格的说append是追加,把一个东西整体加载列表后,而extend是扩展,把一个东西里面的所有元素添加在列表后。

x = ['Monday','Tuesday','Wednessday','Thursday','Friday']
x.extend(['Thursday','Sunny'])
print(x)
print(len(x))

['Monday', 'Tuesday', 'Wednessday', 'Thursday', 'Friday', 'Thursday', 'Sunny']
7

3.list.insert(index,obj)在编号index位置前插入obj。

x = ['Monday','Tuesday','Wednessday','Thursday','Friday']
x.insert(2,'Sunny')
print(x)
print(len(x))

['Monday', 'Tuesday', 'Sunny', 'Wednessday', 'Thursday', 'Friday']
6

7.4 删除列表中的元素

1.list.remove(obj)移除列表中的某个值的第一个匹配项,如下列表中有两个Monday,只是移除了第一个Monday。

x = ['Monday','Tuesday','Monday','Wednessday','Thursday','Friday']
x.remove('Monday')
print(x)
print(len(x))

['Tuesday', 'Monday', 'Wednessday', 'Thursday', 'Friday']
5

2.list.pop([index = -1])移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。

x = ['Monday','Tuesday','Monday','Wednessday','Thursday','Friday']
y =x.pop()
print(y)
y= x.pop(0)
print(y)

print(x)
y = x.pop(-2)
print(y)
print(x)
Friday
Monday
['Tuesday', 'Monday', 'Wednessday', 'Thursday']
Wednessday
['Tuesday', 'Monday', 'Thursday']

remove和pop都可以删除元素,
前者是指定具体要删除的元素,后者是指定一个索引。
3.del var1[,var2 …]删除单个或多个对象
如果你要从列表中删除一个元素,且不再以任何方式使用它,就是用del语句;
如果你要在删除元素后还要继续使用,那就使用方法pop()。

7.5 获取列表中的元素

1.通过元素的索引值,从列表获取单个元素,注意,列表索引值是从0开始的。
2.通过将索引指定为-1,可让python返回最后一个列表元素,索引-2返回倒数第二个列表元素,以此类推。

x = ['Monday','Tuesday','Monday','Wednessday','Thursday','Friday']
print(x[0],type(x[0]))
print(x[-1],type(x[-1]))
print(x[-2],type(x[-2]))

Monday <class 'str'>
Friday <class 'str'>
Thursday <class 'str'>

3.切片的通用写法是start:stop:step
情况1:'start:'以step为1默认的从设备start往列表尾部切片。

x = ['Monday','Tuesday','Wednessday','Thursday','Friday']
print(x[3:])
print(x[-3:])

['Thursday', 'Friday']
['Wednessday', 'Thursday', 'Friday']

情况2:‘:stop’以1默认的从列表头部往编号stop切片。

week = ['Monday','Tuesday','Wednessday','Thursday','Friday']
print(week[:3])
print(x[:-3])

['Monday', 'Tuesday', 'Wednessday']
['Monday', 'Tuesday']

情况3:'start:stop’以step为1默认从编号strat往编号stop切片。

week = ['Monday','Tuesday','Wednessday','Thursday','Friday']
print(week[1:3])
print(x[-3:-1])

['Tuesday', 'Wednessday']
['Wednessday', 'Thursday']

情况4:‘start:stop:step’以具体的step从编号start往编号stop切片。注意最后把step设为-1,相当于将列表反向排列。

week = ['Monday','Tuesday','Wednessday','Thursday','Friday']
print(week[1:4:2])

print(week[:4:2])

print(week[1::2])

print(week[::-1])
['Tuesday', 'Thursday']
['Monday', 'Wednessday']
['Tuesday', 'Thursday']
['Friday', 'Thursday', 'Wednessday', 'Tuesday', 'Monday']

情况5:’:'复制列表汇总的所有元素(浅拷贝)。

week = ['Monday','Tuesday','Wednessday','Thursday','Friday']
print(week[:])

list1 = [123,456,789,213]
list2 = list1
list3 = list1[:]

print(list2)
print(list3)

list1.sort()
print(list1)
print(list2)
print(list3)

list1 = [[123,456],[789,213]]
list2 = list1
list3 = list1[:]
print(list2)
print(list3)
list1[0][0] = 111
print(list2)
print(list3)
['Monday', 'Tuesday', 'Wednessday', 'Thursday', 'Friday']
[123, 456, 789, 213]
[123, 456, 789, 213]
[123, 213, 456, 789]
[123, 213, 456, 789]
[123, 456, 789, 213]
[[123, 456], [789, 213]]
[[123, 456], [789, 213]]
[[111, 456], [789, 213]]
[[111, 456], [789, 213]]

7.6列表的常用操作符

1.等号操作符==
2.连接操作符+
3.重复操作符*
4.成员关系操作符in、not in
[等号==],只有成员、成员位置都相同时才返回True。和元组拼接一样,列表拼接也有两种方式,用[加+]号和[乘号*],前者收尾拼接,后者复制拼接。

list1 = [123,456]
list2 = [456,123]
list3 = [123,456]

print(list1 == list2)
print(list1 == list3)
list4 = list1 + list2
print(list4)

list5 = list3 * 3
print(list5)

list3 *=3
print(list3)

print(123 in list3)
print(456 not in list3)
False
True
[123, 456, 456, 123]
[123, 456, 123, 456, 123, 456]
[123, 456, 123, 456, 123, 456]
True
False

前面三种方法(append,extend,insert)可对列表增加元素,他们没有返回值,是直接修改了原数据的对象。将两个list相加,需要创建新的list对象,从而需要消耗额外的内存,特别是当list较大时,尽量不要使用‘+’来添加list。

7.7 列表的其它方法

1.list.count(obj)统计某个元素在列表中出现的次数

list1 = [123,456] * 3
print(list1)

num = list1.count(123)
print(num)
[123, 456, 123, 456, 123, 456]
3

2.list.index(x[x,start[,end]])从列表转给你找出某个值第一个匹配项的索引位置。

list1 = [123,456] * 5
print(list1.index(123))

print(list1.index(123,1))

print(list1.index(123,3,7))
0
2
4

3.list.reverse()反向列表中的元素

list1 = [123,456,789]
list1.reverse()
print(list1)
[789, 456, 123]

4.list.sort(key = None,reverse = False)对原列表进行排序。
key主要是用来进行比较的元素,只有一个参数,具体的函数参数就是取自于可迭代对象中,指定可迭代对象中的一个元素进行排序。
reverse排序规则,reverse = True降序,reverse = False升序(默认)
该方法没有返回值,但是会对列表的对象进行排序。

x = [123,456,789,213]
x.sort()
print(x)

x.sort(reverse = True)
print(x)

def takeSecond(elem):
    return elem[1]

x = [(2,2),(3,4),(4,1),(1,3)]
x.sort(key = takeSecond)
print(x)

x.sort(key = lambda a:a[0])
print(x)
[123, 213, 456, 789]
[789, 456, 213, 123]
[(4, 1), (2, 2), (1, 3), (3, 4)]
[(1, 3), (2, 2), (3, 4), (4, 1)]

练习题:
1、列表lst 内容如下

lst = [2, 5, 6, 7, 8, 9, 2, 9, 9]

请写程序完成下列操作:
在列表的末尾增加元素15
在列表的中间位置插入元素20
将列表[2, 5, 6]合并到lst中
移除列表中索引为3的元素
翻转列表里的所有元素
对列表里的元素进行排序,从小到大一次,从大到小一次

lst = [2,5,6,7,8,9,2,9,9]
lst.append(15)
print(lst)

lst.insert(5,20)
print(lst)

x = [2,5,6]
lst.append(x)
print(lst)

lst.pop(3)
print(lst)

lst.reverse()
print(lst)

lst =  [2,5,6,7,8,9,2,9,9]
lst.sort()
print(lst)

lst.sort(reverse = True)
print(lst)

[2, 5, 6, 7, 8, 9, 2, 9, 9, 15]
[2, 5, 6, 7, 8, 20, 9, 2, 9, 9, 15]
[2, 5, 6, 7, 8, 20, 9, 2, 9, 9, 15, [2, 5, 6]]
[2, 5, 6, 8, 20, 9, 2, 9, 9, 15, [2, 5, 6]]
[[2, 5, 6], 15, 9, 9, 2, 9, 20, 8, 6, 5, 2]
[2, 2, 5, 6, 7, 8, 9, 9, 9]
[9, 9, 9, 8, 7, 6, 5, 2, 2]

2、修改列表
问题描述:
lst = [1, [4, 6], True]
请将列表里所有数字修改成原来的两倍

def double_list(lst):
    for index, value in enumerate(lst):
        if isinstance(value, bool):
            continue
        if isinstance(value,(int,float)):
            lst[index] *= 2
        if isinstance(value, list):
            #递归
            double_list(value)

if __name__ == '__main__':
    lst = [1, [4, 6], True]
    double_list(lst)
    print(lst)
[2, [8, 12], True]

3、leetcode 852题 山脉数组的峰顶索引
1.A.length >= 3
2.存在 0 < i < A.length - 1 使得A[0] < A[1] < … A[i-1] < A[i] > A[i+1] > … > A[A.length - 1]

给定一个确定为山脉的数组,返回任何满足 A[0] < A[1] < … A[i-1] < A[i] > A[i+1] > … > A[A.length - 1] 的 i 的值。

class Solution(object):
    def peakIndexInMountainArray(self, A):
        return A.index(max(A))
lst= [1,3,4,5,3]
lst2 = [1,2,7,6,4,5]
a = Solution()
#a.peakIndexInMountainArray(lst)
a.peakIndexInMountainArray(lst2)    
2

8 元组

「元组」定义语法为:(元素1, 元素2, …, 元素n)
1.小括号把所有元素绑在一起
2.逗号将每个元素一 一分开

8.1 创建和访问一个元组

1.Python 的元组与列表类似,不同之处在于tuple被创建后就不能对其进行修改,类似字符串。
2.元组使用小括号,列表使用方括号。
3.元组与列表类似,也用整数来对它进行索引 (indexing) 和切片 (slicing)。

t1 = (1,10.31,'python')
t2 = 1,10.31,'python'
print(t1,type(t1))
print(t2,type(t2))
tuple1 = (1,2,3,4,5,6,7,8)
print(tuple1[1])
print(tuple1[5:])
print(tuple1[:5])
tuple2 = tuple1[:]
print(tuple2)
(1, 10.31, 'python') <class 'tuple'>
(1, 10.31, 'python') <class 'tuple'>
2
(6, 7, 8)
(1, 2, 3, 4, 5)
(1, 2, 3, 4, 5, 6, 7, 8)

1.创建元组可以用小括号 (),也可以什么都不用,为了可读性,建议还是用 ()。
2.元组中只包含一个元素时,需要在元素后面添加逗号,否则括号会被当作运算符使用。

temp = (1)
print(type(temp))
temp = 2,3,4,5
print(type(temp))
temp = []
print(type(temp))
temp = ()
print(type(temp))
temp = (1,)
print(type(temp))
<class 'int'>
<class 'tuple'>
<class 'list'>
<class 'tuple'>
<class 'tuple'>
print(8 * (8))
print( 8 * (8,))
print((8,) *8)
64
(8, 8, 8, 8, 8, 8, 8, 8)
(8, 8, 8, 8, 8, 8, 8, 8)

创建二维元组,并且元组中可以使用整数来对它进行索引和切片、不严谨的讲,前者是获取单个元素,后者是获取一组元素,如下例:

nested = (1,10.31,'python'),('data',11)
print(nested)
print(nested[0])
print(nested[0][0],nested[0][1],nested[0][2])
print(nested[0][0:2])
((1, 10.31, 'python'), ('data', 11))
(1, 10.31, 'python')
1 10.31 python
(1, 10.31)

8.2更新和删除一个元组

week = ('Monkey','Tuesday','Thursday','Friday')
week = week[:2] + ('Wednessday',) + week[2:]
print(week)
('Monkey', 'Tuesday', 'Wednessday', 'Thursday', 'Friday')
t1 = (1,2,3,[4,5,6])
print(t1)

t1[3][0] = 9
print(t1)
(1, 2, 3, [4, 5, 6])
(1, 2, 3, [9, 5, 6])

元组有不可更改 (immutable) 的性质,因此不能直接给元组的元素赋值,但是只要元组中的元素可更改 (mutable),那么我们可以直接更改其元素,注意这跟赋值其元素不同。

8.3 元组相关操作符

1.比较操作符
2.逻辑操作符
3.连接操作符+
4.重复操作符*
5.成员关系操作符in,not in
元组拼接有两种方式,用「加号 +」和「乘号 *」,前者首尾拼接,后者复制拼接。

t1 = (2,3,4,5)
t2 = ('老马的程序人生','小马的程序人生')
t3 = t1 + t2
print(t3)
t4 = t2 * 2
print(t4)
(2, 3, 4, 5, '老马的程序人生', '小马的程序人生')
('老马的程序人生', '小马的程序人生', '老马的程序人生', '小马的程序人生')

8.4 内置方法

元组大小和内容都不可更改,因此只有 count 和 index 两种方法。

t = (1,10.31,'python')
print(t.count('python'))
print(t.index(10.31))
1
1

count(‘python’) 是记录在元组 t 中该元素出现几次,显然是 1 次
index(10.31) 是找到该元素在元组 t 的索引,显然是 1

8.5 解压元组

解压(unpack)一维元组(有几个元素左边括号定义几个变量)

t = (1,10.31,'python')
(a,b,c) = t
print(a,b,c)
1 10.31 python

解压二维元组(按照元组里的元组结构来定义变量)

t = (1,10.31,('OK','python'))
(a,b,(c,d)) = t
print(a,b,c,d)
1 10.31 OK python

如果你只想要元组其中几个元素,用通配符「*」,英文叫 wildcard,在计算机语言中代表一个或多个元素。下例就是把多个元素丢给了 rest 变量。

t = 1,2,3,4,5
a,b,*rest,c = t
a,b,*_  =t
print(a,b,c)
print(rest)
print(a,b)
1 2 5
[3, 4]
1 2

练习题:
1、

t1 = (1,2)*2
t2 = (1,) * 2
t3 = (1) * 2
print(t1,type(t1))
print(t2,type(t2))
print(t3,type(t3)) 
(1, 2, 1, 2) <class 'tuple'>
(1, 1) <class 'tuple'>
2 <class 'int'>

2、
不属于

9 字符串

9.1字符串的定义

1.python中的字符串被定义为引号之间的字符集合
2.python支持使用成对的单引号或双引号。

t1 = 'i love python'
print(t1,type(t1))

t2 = 'I love python'
print(t2,type(t2))
print(5+8)
print('5' + '8')
i love python <class 'str'>
I love python <class 'str'>
13
58

1.如果字符串中需要出现单引号或双引号,可以使用转义字符\对字符串中的符号进行转义。

print('let\'s go')
print("let's go")
print('C:\\now')
print("C:\\Program Files\\Intel\\Wifi\\Help")
let's go
let go
c:\now
C:\Program Files\Intel\Wifi\Help

1.python的常用转义字符
转义字符 描述
\\ 反斜杠符号
’ 单引号
‘’ 双引号
\n 换行
\t横向制表符
\r回车

1.原始字符串只要在字符串前边加上一个英文字母r即可。

print(r"C:\Program Files\Intel\Wifi\Help")
C:\Program Files\Intel\Wifi\Help

2.python三引号允许一个字符串跨多行,字符串中可以包含换行符,制表符以及其他特殊字符。

para_str = """ 这是一个多行字符串的实例
多行字符串可以使用制表符
TAB(\t)。
也可以使用换行符[\n]""" 
print(para_str)
这是一个多行字符串的实例
多行字符串可以使用制表符
TAB(	)。
也可以使用换行符[
]

9.2 字符串的切片与拼接

1.类似于元组具有不可修改性
2.从0开始(和C一样)
3.切片通常写成start:end这种形式,包括[start]索引对应的元素,
不包括[end]索引对应的元素
4.索引值可正可负,正索引从0开始,从左往右;负索引从-1开始,从右往左。使用负数索引时,会从最后一个元素开始计数。最后一个元素的位置编号是-1。

str1 = 'I love LsgoGroup'
print(str1[:6])
print(str1[5])
print(str1[:6] + "插入的字符串" + str1[6:])


s = 'python'
print(s)
print(s[2:4])
print(s[-5:-2])
print(s[2])
print(s[-1])
I love
e
I love插入的字符串 LsgoGroup
python
th
yth
t
n

9 .3 字符串的常用内置方法

1.capitalize()将字符串的第一个字符转换为大写

str2 = 'xiaoxie'
print(str2.capitalize())
Xiaoxie

1.lower()转换字符串中的所有大小写字符为小写。
2.upper()转换字符串中的小写字母为大写。
3.swapcase()将字符串中的大写转换为小写,小写转换为大写。

str2 = "DAXIExiaoxie"
print(str2.lower())
print(str2.upper())
print(str2.swapcase())   
daxiexiaoxie
DAXIEXIAOXIE
daxieXIAOXIE  

1.count(str,beg = 0,end = len(string)),返回str在string里面出现的次数,如果beg或者end指定则返回指定的范围内的str出现的次数。

str2 = "DAXIExiaoxie"
print(str2.endswith('ie'))
print(str2.endswith('xi'))
print(str2.startswith('Da'))
print(str2.startswith('DA'))
True
False
False
True

1.find(str,beg = 0,end = len(string))检测str是否包含在字符串中,如果指定范围beg和end,则检查时候包含在指定的范围内,如果包含,则返回开始的索引值,否则返回-1。
2.rfind(str,beg = 0,end = len(string))类似于find()函数,不过是从右边开始查找。

str2 = "DAXIExiaoxie"
print(str2.find('xi'))
print(str2.find('ix'))
print(str2.rfind('xi'))
5
-1
9

1.isnumeric()如果字符串中包含数字字符,则返回True,否则返回False。

str3 = '12345'
print(str3.isnumeric())
str3 += 'a'
print(str3)
print(str3.isnumeric())
True
12345a
False

1.ljust(width[ , fillchar])返回一个原字符串左对齐,并使用fillchar(默认空格)填写至长度width的新字符串。
2.rjust(width[ , fillchar])返回一个原字符串右对齐,并使用fillchar(默认空格)填写至长度width的新字符串。

str5 = ' I love LsgoGroup '
print(str5.lstrip())
print(str5.lstrip().strip('I'))
print(str5.rstrip())
print(str5.strip())
print(str5.strip().strip('p'))
I love LsgoGroup 
 love LsgoGroup 
 I love LsgoGroup
I love LsgoGroup
I love LsgoGrou

1 .partition(sub)找到子字符串sub,把字符串分为一个三元组(pre_sub,sub,fol_sub),如果字符串中不包含sub则返回(‘原字符串’,’ ‘,’ ')。
2.rpartition(sub)类似于partition()方法,不过是从右边开始查找。

str5 = ' I love LsgoGroup '
print(str5.strip().partition('o'))
print(str5.strip().partition('m'))
print(str5.strip().rpartition('o'))
('I l', 'o', 've LsgoGroup')
('I love LsgoGroup', '', '')
('I love LsgoGr', 'o', 'up')

1.replace(old,new[, max])将字符串中的old替换成new,如果max指定,则替换不超过max次。

str5 = ' I love LsgoGroup '
print(str5.strip().replace('I','We'))
We love LsgoGroup

1.split(str = " ",num)不带参数默认是以空格为分隔符切片字符串,如果num参数有设置,则紧分割num个子字符串,返回切片后的子字符串拼接的列表。

str5 = ' I love LsgoGroup '
print(str5.strip().split())
print(str5.strip().split('o'))
['I', 'love', 'LsgoGroup']
['I l', 've Lsg', 'Gr', 'up']
u = "www.baidu.com.cn"
print(u.split())
print(u.split('.'))
print(u.split('.',0))
print(u.split('.',1))
print(u.split('.',2))
print(u.split('.',2)[1])
u1,u2,u3 = u.split('.',2)
print(u1)
print(u2)
print(u3)
['www.baidu.com.cn']
['www', 'baidu', 'com', 'cn']
['www.baidu.com.cn']
['www', 'baidu.com.cn']
['www', 'baidu', 'com.cn']
baidu
www
baidu
com.cn

去掉换行符

c= ''' say
hello
baby'''
print(c)
print(c.split('\n'))
say
hello
baby
['say', 'hello', 'baby']
string = " hello boy<[www.baidu.com]>byebye"
print(string.split('[')[1].split(']')[0])
print(string.split('[')[1].split(']')[0].split('.'))
www.baidu.com
['www', 'baidu', 'com']

1.splitlines([keepends])按照行(’\r’,’\r\n’,’\n’)分隔,返回一个包含各行作为元素的列表,如果参数keepends为False,不包含换行符;如果为True,则保留换行符。

str6 = 'I \n Love \n LsgoGroup'
print(str6.splitlines())
print(str6.splitlines(True))
['I ', ' Love ', ' LsgoGroup']
['I \n', ' Love \n', ' LsgoGroup']

1.maketrans(intab,outtab)创建字符映射的转换表,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。
2.translate(table,deletechars = ‘’)根据参数table给出的表,转换字符串的字符,要过滤掉的字符放到deletechars参数中。

str = 'this is string example....wow!!!'
intab = 'aeiou'
outtab = '12345'
trantab = str.maketrans(intab,outtab)
print(trantab)
print(str.translate(trantab))
{97: 49, 101: 50, 105: 51, 111: 52, 117: 53}
th3s 3s str3ng 2x1mpl2....w4w!!!

9.4 字符串格式化

1.python format格式化函数

str = "{0} Love {1}".format('I','Lsgogroup')#位置参数
print(str)

str = "{a} Love {b}".format(a = 'I',b = 'Lsgogroup')#关键字参数
print(str)

str = "{0} Love {b}".format('I',b ='Lsgogroup')
print(str)

str = '{0:.2f}{1}'.format(27.658,'GB')
I Love Lsgogroup
I Love Lsgogroup
I Love Lsgogroup
27.66GB

1.python字符串格式化符号
符号 描述
%c 格式化字符及其ASCII码
%s 格式化字符串,用str()方法处理对象
%r 格式化字符串,用rper()方法处理对象
%d 格式化整数
%o 格式化无符号八进制数
%x 格式化无符号十六进制数
%X 格式化无符号十六进制数(大写)
%f 格式化浮点数字,可指定小数点后的精度
%e 用科学计数法格式化浮点数
%E 作用同%e,用科学计数法格式化浮点数
%g 根据值的大小决定使用%f或%e
%G 作用同%g,根据值的大小决定使用%f或%

print('%c'%97)
print('%c %c %c'%(97,98,99))
print('%d + %d = %d'%(4,5,9))
print("我叫 %s 今年 %d 岁!" %('小明',10))
print('%o'%10)
print('%x'%10)
print('%X'%10)
print('%f' % 27.658)
print('%e' % 27.658)
print('%E' % 27.658)
print('%g' % 27.658)
text = "I am %d years old."% 22
print("I said:%s." % text)
print("I said:%r." % text)
a
a b c
4 + 5 = 9
我叫 小明 今年 10!
12
a
A
27.658000
2.765800e+01
2.765800E+01
27.658
I said:I am 22 years old.
I said:'I am 22 years old.'

1.格式化辅助字符指令
符号 功能
m.n m 是显示的最小总宽度,n 是小数点后的位数(如果可用的话)
[-] 用作左对齐
[+] 在正数前面显示加号( + )
#在八进制数前面显示零(‘0’),在十六进制前面显示’0x’或者’0X’(取决于用的是’x’还是’X’)
0 显示的数字前面填充’0’而不是默认的空格

print('%5.1f' % 27.658)  
print('%.2e' % 27.658)  
print('%10d' % 10) 
print('%-10d' % 10)      
print('%+d' % 10)  
print('%#o' % 10)  
print('%#x' % 108)  
print('%010d' % 5)  
 27.7
2.77e+01
        10
10        
+10
0o12
0x6c
0000000005

练习题:
1.
使用replace(old,new)函数
使用split(str = " ",num)函数
使用lstrip()函数
2.

def isdigist(s):
    try:
        float(s)
        return True
    except ValueError:
        pass
    try:
        import unicodedata
        unicodedata.numeric(s)
        return True
    except (TypeError, ValueError):
        pass
    return False

你可能感兴趣的:(python 学习第四天 列表、元组和字符串)