- 数据结构
- 字符串
- 列表
- 元组
- 字典
- 栈
- 队列
- 集合
-
字符串
- 创建字符串
str1 = "Hello world!" str2 = "ABCDEFG"
- 访问
- 左闭右开
str1 = "Hello world!" # 访问字符串中的单个字符或者子串 print('str1:', str1) print('str1[0]:', str1[0]) print('str1[0:5]:', str1[0:5]) print('str1[6:11]:', str1[6:11]) print('str1[-1]:', str1[-1]) print('str1[9:10]:', str1[9:10]) print('str1[-2:-1]:', str1[-2:-1])
- 修改字符串
- replace(old,new)
- 不支持通过索引修改
- 字符串拼接
str1 = "Hi!" str2 = "Jack" # 通过拼接修改字符串 str1 = str1 + str2 print('After splicing str1:', str1) # 通过替换修改字符串:replace(old,new) str1 = str1.replace(str2, "Tom") print('After replacement str1:', str1)
- 字符串运算符
- 拼接
- 剪切
- 复制
- 成员运算
str1 = "Hello world!" str2 = "Jack" # 字符串拼接 print('str1+str2:', str1 + str2) # 字符串截取 print('str1[0:6]:', str1[0:6]) # 字符串复制 print('str2*2:', str2 * 3) # 成员运算:判断一个字符串是否包含某成员 print('world in str1?', 'world' in str1) print('word in str1?', 'word' in str1)
- 字符串格式化
#格式化为十进制:%d print('PI is approximately equal to %d (I)'%(3.1415926)) #格式化字符串:%s print('PI is approximately equal to %s (II)'%(3.1415926)) #格式化浮点数字,可指定小数点后的精度,默认为6位小数:%f print('PI is approximately equal to %f (III)'%(3.1415926)) #格式化浮点数字,指定n位小数:%.nf print('PI is approximately equal to %.2f (IV)'%(3.1415926)) #用科学计数法格式化浮点数:%e print('PI is approximately equal to %e (V)'%(3.1415926)) #格式化为十进制:%d print('The road is about %d meters long (VI)'%(1234)) #格式化无符号八进制数:%d print('The road is about %o meters long (VII)'%(1234)) #格式化无符号十六进制数:%x print('The road is about %x meters long (VIII)'%(1234))
- 创建字符串