字符串str
按索引下标查找
str = 'Hi, world, follow, admin'
print ( str [ 0 ] )
print ( str [ - 1 ] )
index()
str = 'Hi, world, follow, admin'
print ( str . index( 'world' ) )
print ( str . index( 'w' ) )
字符串.replace(字符串1,字符串2):将字符串内的"全部"字符串1替换为字符串2
字符串内容无法修改,replace方法会得到一个新的字符串
str1 = 'Hi, world, follow, admin'
new_str = str1. replace( 'w' , 'W' )
print ( f"将 { str1} 执行替换操作后得到: { new_str} " )
字符串.split(分割字符符串):按指定的分隔符字符串,将字符串划分为多个字符串,并存入列表 对象中
str = 'Hi, world, follow, admin'
my_list = str . split( ',' )
print ( f"将 { str } 按逗号切分后为: { my_list} ,类型为: { type ( my_list) } " )
strip()方法:默认去除字符串前后空格;若传入参数,去除指定字符
str1 = ' java python c c++ '
new_str = str1. strip( )
print ( f"str1: { str1} 使用Strip()方法后为: { new_str} " ) str2 = '123java python c c++112233'
new_str = str2. strip( "123" )
print ( f"str2: { str2} 使用Strip()方法后为: { new_str} " ) str3 = '123java python c c++112233 123'
new_str = str3. strip( "123" )
print ( f"str3: { str3} 使用Strip()方法后为: { new_str} " ) str4 = ' 123java python c c++112233 123'
new_str = str4. strip( "123" )
print ( f"str4: { str4} 使用Strip()方法后为: { new_str} " )
count()方法,len()方法
str = ' 123java python c c++112233 123'
print ( f"'123'的个数为: { str . count( '123' ) } " )
print ( "字符串长度为:" , len ( str ) )
字符串遍历
str = 'java python c'
i = 0
while i < len ( str ) : print ( "while循环遍历:" , str [ i] ) i += 1 for element in str : print ( f"for循环遍历: { element} " )
序列:列表、元组、字符串
序列切片
序列[起始下标:结束下标:步长]:左闭右开[起始,结束)
my_list = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ]
my_tuple = ( 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 )
my_str = '12345678'
print ( "my_list[1,3):" , my_list[ 1 : 3 ] )
print ( "my_tuple:" , my_tuple[ : ] )
print ( "my_str步长为2切片:" , my_str[ : : 2 ] )
my_list = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ]
my_tuple = ( 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 )
my_str = '12345678'
print ( "my_str逆序:" , my_str[ : : - 1 ] )
print ( "my_tuple步长为2逆序切片:" , my_tuple[ : : - 2 ] )
print ( "my_list(1,3]逆序切片:" , my_list[ 3 : 1 : - 1 ] )
小结
实战,将python切片,逆序输出
str = 'java python3 c++'
new_str = str [ 5 : 11 ] [ : : - 1 ]
print ( new_str)
new_str = str [ : : - 1 ] [ 5 : 11 ]
print ( new_str)
new_str = str [ 10 : 4 : - 1 ]
print ( new_str)
new_str = str . split( ' ' ) [ 1 ] . replace( '3' , '' ) [ : : - 1 ]
print ( new_str)