字符串 String
字符串是 Python 中最常用的数据类型。我们可以使用引号('或")来创建字符串。
Python不支持单字符类型,单字符在 Python 中也是作为一个字符串使用。
Python访问子字符串,可以使用方括号来截取字符串,如下实例
var1 = 'Hello World!'
var2 = "Python Runoob"
print("var1[0]: ", var1[0])
print("var2[1:5]: ", var2[1:5])
var1[0]: H
var2[1:5]: ytho
字符串的方法 “str”
“”.index
匹配子字符串,并返回第一配置项的索引位置
a = "hello ! my name is chenhuaicong!!!"
print(a.index("my"))
8
“”.count
统计子字符串在匹配的次数
a = "hello ! my name is chenhuaicong!!!"
print(a.count("h"))
“”.replace
替换
a = "hello ! my name is chenhuaicong!!!"
print(a.replace("my","your"))
hello ! your name is chenhuaicong!!!
“”.strip
前后去空格
a = " hello ! my name is chenhuaicong!!! "
print(a.strip())
hello ! my name is chenhuaicong!!!
” “.join
(可迭代对象) 将新字符串加入到字符串中
a = "hello ! my name is chenhuaicong!!!"
print("-".join(a))
h-e-l-l-o- -!- -m-y- -n-a-m-e- -i-s- -c-h-e-n-h-u-a-i-c-o-n-g-!-!-!
“”.split
分割
a = "hello ! my name is chenhuaicong!!!"
print(a.split(" "))
['hello', '!', 'my', 'name', 'is', 'chenhuaicong!!!']
“”.format
字符串格式化
a = "hello ! my name is chenhuaicong!!!"
b = "the boy said: {0}".format(a)
print(b)
列表
列表是由一序列特定顺序排列的元素组成的。可以把字符串,数字,字典等都可以任何东西加入到列表中,日中的元素之间没有任何关系。列表也是自带下标的,默认也还是从0开始
列表的方法 list()
[].append
在列表的末尾添加新的对象
k = [1,2,3,4,5,6,7,1,23,45]
k.append("chenhuaicong")
print(k)
[1, 2, 3, 4, 5, 6, 7, 1, 23, 45, 'chenhuaicong']
[].count
统计列表中元素出现的次数
k = [1,2,3,4,5,6,7,1,5,23,45,5]
print(k.count(5))
3
[].extend
在列表的末尾追加另外一个列表
k = [1,2,3,4,5,6,7,1,5,23,45,5]
q = ["我","abc",4,6]
k.extend(q)
print(k)
[1, 2, 3, 4, 5, 6, 7, 1, 5, 23, 45, 5, '我', 'abc', 4, 6]
[].index
从列表中找出某个值第一个匹配项的索引位置
k = [1,2,3,4,5,6,7,1,5,23,45,5]
print(k.index(3))
2
[].insert
将对象插入列表
k = [1,2,3,4,5,6,7,1,5,23,45,5]
k.insert(3,"hello")
print(k)
[1, 2, 3, 'hello', 4, 5, 6, 7, 1, 5, 23, 45, 5]
[].pop
移除列表中的一个元素,默认是最后一个元素,并且返回改元素的值
k = [1,2,3,4,5,6,7,1,5,23,45,5]
print(k.pop())
print(k)
5
[1, 2, 3, 4, 5, 6, 7, 1, 5, 23, 45]
k = [1,2,3,4,5,6,7,1,5,23,45,5]
print(k.pop(5))
print(k)
6
[1, 2, 3, 4, 5, 7, 1, 5, 23, 45, 5]
[].remove
移除列表中某个值的第一匹配项
k = [1,2,3,4,5,6,7,1,5,23,45,5]
k.remove(5)
print(k)
[1, 2, 3, 4, 6, 7, 1, 5, 23, 45, 5]
[].reverse
反转列表中的元素
k = [1,2,3,4,5,6,7,1,5,23,45,5]
k.reverse()
print(k)
[5, 45, 23, 5, 1, 7, 6, 5, 4, 3, 2, 1]
[].sort
对原列表进行排序
k = [1,2,3,4,5,6,7,1,5,23,45,5]
k.sort()
print(k)
[1, 1, 2, 3, 4, 5, 5, 5, 6, 7, 23, 45]
元组
定义:Tuple就是不可变的list
元组tuple()
().index(x)
查找某元素,并返回该元素的索引位置
a = ("a","b","c","d","e","f","g")
print(a.index("c"))
2
().count(x)
统元素出现的次数
a = ("a","b","c","d","e","f","g","c")
print(a.count("c"))
2