1:strip()方法, 去除字符串开头或者结尾的空格 >>> a = " a b c " >>> a.strip() ‘a b c‘ 2:lstrip()方法, 去除字符串开头的空格 >>> a.lstrip() ‘a b c ‘ 3:rstrip()方法, 去除字符串结尾的空格 >>> a.rstrip() ‘ a b c‘ 4:replace()方法, 可以去除全部空格 # replace主要用于字符串的替换replace(old, new, count) >>> a = " a b c " >>> a.replace(" ", "") ‘abc‘ 5: join()方法+split()方法, 可以去除全部空格 # join为字符字符串合成传入一个字符串列表,split用于字符串分割可以按规则进行分割 # 字符串按空格分割成列表 >>> b [‘a‘, ‘b‘, ‘c‘] >>> c = "".join(b) # 使用一个空字符串合成列表内容生成新的字符串 >>> c ‘abc‘ # 快捷用法 >>> a = " a b c " >>> "".join(a.split()) ‘abc‘ 原文:https://www.cnblogs.com/fandx/p/9311755.html
1倒序输出 s = 'abcde' print ( s [::- 1 ]) #输出: 'edcba' 2 列表reverse()操作 s = 'abcde' lt = list ( s ) lt . reverse () print ( '' . join ( lt )) #输出: 'edcba' 3 二分法交换位置 s = 'abcde' lt = list ( s ) for i in range ( len ( l ) // 2 ): lt [ i ], lt [-( i + 1 )] = lt [-( i + 1 )], lt [ i ] print ( '' . join ( lt )) #输出: 'edcba' 4 列表生成式 s = 'abcde' print ( '' . join ([ s [ i - 1 ] for i in range ( len ( s ), 0 , - 1 )])) #输出: 'edcba' 5 栈的思想 s = 'abcde' lt = list ( s ) res = '' while lt : res += lt . pop () print ( res ) #输出: 'edcba' 6 递归的思路 def res_str ( s ) : if len ( s ) == 1 : return s head = s [ 0 ] tail
def str_to_hex (s) : return ' ' .join([hex(ord(c)).replace( '0x' , '' ) for c in s]) def hex_to_str (s) : return '' .join([chr(i) for i in [int(b, 16 ) for b in s.split( ' ' )]]) def str_to_bin (s) : return ' ' .join([bin(ord(c)).replace( '0b' , '' ) for c in s]) def bin_to_str (s) : return '' .join([chr(i) for i in [int(b, 2 ) for b in s.split( ' ' )]]) 文章来源: Python字符串转十六进制进制互转