字符串定义
和tuple一样是一个无法修改的数据容器
my_str = "one and two"
通过下标索引取值
my_str = "one and two
取one中的n
正向索引:value = my_str[2]
反向索引:value = my_str[-10]
index方法
my_str = "one and two
value = my_str.index("and"
返回:4(and的起始下标)
字符串的替换
语法:字符串.replace(字符串1,字符串2)
new_my_str = my_str.replace("on', "加油)
结果:new_my_str = “加油e and two”
功能:将字符串内的全部:字符串1,替换为字符串2(不是修改字符串本身,而是得到了一个新的字符串,字符串是不可修改的)
字符串的分割
语法:字符串.split(分隔字符串)
功能:按照指定的分隔符字符串,将字符串划分为多个字符串,并存入列表对象中(注意:字符串本身不变,而是得到了一个列表对象)
my_str = "hello one two three"
my_str_list = my_str.split(" ")
结果:[‘hello’, ‘one’, ‘two’, ‘three’]
字符串的规整操作
- 去前后空格
语法:字符串.strip()
my_str = " hello one two three "
print(my_str.strip( )) # 结果:"hello one two three"
- 去前后指定字符串
语法:字符串.strip(字符串)
my_str = "12hello one 12two three21"
print(my_str.strip("12")) #结果:"hello one 12two three"
(不是将12看做字符串,而是吧1,2单独看,满足其一就去除,且只能去除首尾的元素,不能去除中间的)
统计字符串的长度:len( )
num = len(my_str)