字符串
字符串的分片和索引
字符串的索引类似于列表,就像下面这样:
string1='hello world'
print(string1[2])
# 'l'
print(string1[-1])
# 'd'
上面的代码运行结果可以很清楚的体现出字符串的索引对应,从左到右从0开始,而从右到左则从-1开始
字符串的切片也和列表类似,不多说,直接上例子:
string1='hello world'
print(string[2:5])
# 'llo'
print[:-5]
# 'hello'
字符串的格式化符
Python中我们经常使用.format()函数来实现字符串填空,具体使用如下面例子:
print('{} agreed this idea.'.format(input('who agreed this idea?'))
当你输入某个人时,结果就会输出这个人同意这个观点,这就是字符串的填空
序列
常见序列类型包括字符串、列表和元组,这些序列类型的共同特点就是都可以通过索引值获取相应元素,不过值得注意的是元组不能切片和增删修改,而其他序列类型则可以,之前以前写过了这些序列的主要性质,这里我想举一个可以应用于各种序列的函数len(),它可以统计字符串的长度,列表和元组的元素个数,下面上代码:
print(len('family'))
# 6
list=[1,'my',[1,2]]
print(len(list))
# 3
tuple=(1,'my',[1,2])
print(len(tuple))
# 3