列表
基本操作
- 访问列表中的值
list = ['c','c++','java','python']
print(list[1:3])
运行结果
['c++', 'java']
- 更新列表
list[3] = 'python3'
print(list[3])
运行结果
python3
- 操作符
表达式 | 结果 | 说明 |
---|---|---|
len([1,2,3]) | 3 | 长度 |
[1,2]+[3,4] | [1,2,3,4] | 组合 |
[1,2]*2 | [1,2,1,2] | 重复 |
常用方法
- append(obj)
在列表末尾添加新对象
list.append('go')
print(list)
运行结果
['c', 'c++', 'java', 'python3', 'go']
- remove(obj)
删除某个对象的第一个匹配项
list.remove('java')
print(list)
运行结果
['c', 'c++', 'python3', 'go']
- copy()
复制列表
list1 = list.copy()
print(list1)
运行结果
['c', 'c++', 'python3', 'go']
- list(seq)
将元组转换为列表
tuple = (1,2,3)
list2 = list(tuple)
print(tuple)
print(list2)
(1, 2, 3)
[1, 2, 3]
元组
基本操作
Python 的元组与列表类似,不同之处在于元组的元素不能修改。
元组使用小括号,列表使用方括号。
- 访问元组
tup = ('c','c++','java','python')
print(tup[1:3])
运行结果
('c++', 'java')
- 删除元组
元组中的元素值是不允许删除的,但可以使用del语句来删除整个元组
del tup
print(tup)
运行结果
NameError: name 'tup' is not defined
操作符同list
字符串
字符串特殊运算符
- r/R
原始字符串,所有字符原样打印,忽略转义字符等特殊字符
str = '12\n34'
str1 = r'12\n34'
print(str)
print(str1)
运行结果
12
34
12\n34
- %
格式字符串,与 C 中 printf 函数一样的语法
符号 | 说明 |
---|---|
%c | 格式化字符及其ASCII码 |
%s | 格式化字符串 |
%d | 格式化整数 |
%u | 格式化无符号整型 |
%o | 格式化无符号八进制数 |
%x | 格式化无符号十六进制数 |
%X | 格式化无符号十六进制数(大写) |
%f | 格式化浮点数字,可指定小数点后的精度 |
%e/E | 用科学计数法格式化浮点数 |
%g/G | %f和%e/E的简写 |
%p | 用十六进制数格式化变量的地址 |
- 三引号
python三引号允许一个字符串跨多行,字符串中可以包含换行符、制表符以及其他特殊字符,所见即所得
str2 = """这是一个多行字符串的实例
多行字符串可以使用制表符
TAB ( \t )。
也可以使用换行符 [ \n ]。
"""
print (str3)
运行结果
这是一个多行字符串的实例
多行字符串可以使用制表符
TAB ( )。
也可以使用换行符 [
]。
常用方法
- find(str, beg=0, end=len(string))
检测 str 是否包含在字符串中,如果指定范围 beg 和 end ,则检查是否包含在指定范围内,如果包含返回开始的索引值,否则返回-1
str = 'hello,world!'
print(str.find('world'))
运行结果
6
- index(str, beg=0, end=len(string))
跟find()方法一样,只不过如果str不在字符串中会报一个异常.
str = 'hello,world!'
print(str.index('you'))
运行结果
ValueError: substring not found
- lstrip() (同理有rstrip(),strip())
截掉字符串左边的空格或指定字符。
str = ' hello,world!'
print(str)
print(str.lstrip())
运行结果
hello,world!
hello,world!
- replace(old, new [, max])
将字符串中的 str1 替换成 str2,如果 max 指定,则替换不超过 max 次。
str = 'hello,world!'
print(str.replace('world','python'))
运行结果
hello,python!
- swapcase() (同理有upper(),lower())
将字符串中大写转换为小写,小写转换为大写
str = 'Hello,World!'
print(str.swapcase())
运行结果
hELLO,wORLD!
- split(str="", num=string.count(str))
以 str 为分隔符截取字符串,如果 num 有指定值,则仅截取 num+1 个子字符串
str = 'hello,world!,hello,python'
print(str.split(','))
运行结果
['hello', 'world!', 'hello', 'python']