本帖最后由 咸鱼之王66 于 2018-10-8 08:30 编辑
1 +、* 操作适用于字符串、列表、元组(不适用于集合与字典) str1 = "123456"
str2 = "789"
list1 = [1, 2, 3, 4, 5, 6]
list2 = [7, 8, 9]
tuple1 = (1, 2, 3, 4, 5, 6)
tuple2 = (7, 8, 9)
# 运算
str3 = str1 + str2
list3 = list1 + list2
tuple3 = tuple1 + tuple2
str4 = str1*2
list4 = list1*2
tuple4 = tuple1*2
# 输出
print(str3)
print(list3)
print(tuple3)
print(str4)
print(list4)
print(tuple4) 运行结果 123456789 [1, 2, 3, 4, 5, 6, 7, 8, 9] (1, 2, 3, 4, 5, 6, 7, 8, 9) 123456123456 [1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6] (1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6)
2 字符串、列表、元组的两种索引与切片(不适用于集合与字典) 第一种:从左往右,索引从0开始,依次增大1 第二种:从右往左,索引从-1开始,依次减小1 str1 = "123456"list1 = [1, 2, 3, 4, 5, 6]
tuple1 = (1, 2, 3, 4, 5, 6)
set1 = {1, 2, 3, 4, 5, 6}
# 切片
str2 = str1[1:3]
list2 = list1[1:3]
tuple2 = tuple1[1:3]
str3 = str1[-4:-2]
list3 = list1[-4:-2]
tuple3 = tuple1[-4:-2]
# 输出
print(str2)
print(list2)
print(tuple2)
print(str3)
print(list3)
print(tuple3)运行结果 23 [2, 3] (2, 3) 34 [3, 4] (3, 4)
|