字符串-str
下标index和切片
"""
所谓“下标”,就是编号,就好比超市中的存储柜的编号,通过这个编号就能找到相应的存储空间
列表与元组支持下标索引好理解,字符串实际上就是字符的数组,所以也支持下标索引。
如果想取出部分字符,那么可以通过下标的方法.
p y t h o n
0 1 2 3 4 5 正向取值,下标第一位为0
-6 -5 -4 -3 -2 -1 倒序取值,下标第一位为-1
s = "Never stop learning!"
说明: “位置”指的是字符所处的位置(比如位置1,指的是第一个字符“N”),
“索引”指的是字符的索引值(比如索引0,代表的是第一个字符“N”)
开始位置,是指字符串起始,即下标为0开始。
末尾,是指字符串最后。
"""
s = "Never stop learning!"
indexes = s[ 0 ]
print ( indexes)
"""
切片是指对字符串截取其中一部分的操作。字符串、列表、元组都支持切片操作。
切片格式:字符串[起始索引:结束索引:步长]
注意:选取的区间属于“左闭右开型”,即从"起始"位开始,到"结束"位的前一位结束(不包含结束位本身)。
"""
print ( s[ : 3 ] )
print ( s[ : ] )
print ( s[ 2 : ] )
print ( s[ : : 2 ] )
print ( s[ 1 : : 2 ] )
print ( s[ : : ] )
print ( s[ : : - 1 ] )
"""
输出结果
Nev
Never stop learning!
ver stop learning!
Nvrso erig
ee tplann!
Never stop learning!
!gninrael pots reveN
"""
split() 分隔符切片
split_str = "Google#Runoob#Taobao#Facebook"
print ( split_str. split( "#" ) )
print ( split_str. split( '#' , 2 ) )
"""
输出结果:
['Google', 'Runoob', 'Taobao', 'Facebook']
['Google', 'Runoob', 'Taobao#Facebook']
"""
s = '<script src="https://g.csdnimg.cn/common/csdn-toolbar/csdn-toolbar.js" type="text/javascript"></script>'
print ( eval ( s. split( "=" ) [ 1 ] . split( " " ) [ 0 ] ) )
join()/+ 拼接
str1 = "123"
str2 = "abc"
print ( str1. join( str2) )
print ( str1+ str2)
"""
输出结果:
a123b123c
123abc
"""
seq4 = { "hello" : 1 , "girls" : 2 , "welcome" : 3 , "to" : 4 , "China" : 5 }
print ( " " . join( seq4) )
strip() 删除
str = "123abcrunoob32"
print ( str . strip( '12' ) )
str = "00000003210Runoob01230000000" ;
print ( str . strip( '0' ) )
print ( str . lstrip( "0" ) )
print ( str . rstrip( "0" ) )
str2 = " Runoob b "
print ( str2. strip( ) )
"""
输出结果:
3abcrunoob3
3210Runoob0123
3210Runoob01230000000
00000003210Runoob0123
Runoob b
"""
find() 查找
info = 'abca'
print ( info. find( 'a' ) )
print ( info. find( 'a' , 1 ) )
print ( info. find( '3' ) )
replace() 替换
str1 = 'is is is is'
print ( str1. replace( "is" , "was" ) )
print ( str1. replace( "is" , "was" , 2 ) )
"""
输出结果:
was was was was
was was is is
"""
endswith()/startwith()
s = "Never stop learning!"
print ( s. startswith( "Ne" ) )
print ( s. startswith( "Ne" , 1 ) )
print ( s. startswith( "ev" , 1 , 5 ) )
print ( s. endswith( "!" ) )
print ( s. endswith( "!" , 0 , 10 ) )
lower()/upper() 大小写转换
s = "Never stop learning!"
print ( s. lower( ) )
print ( s. upper( ) )
"""
输出结果:
never stop learning!
NEVER STOP LEARNING!
"""
len() 长度
print ( len ( s) )