字符串处理
拆分含有多种分隔符 的字符串
单一分割符:split( ) 进行分割
#字符串中多个分隔符分割 #方法一 通过循环,用split方法分割 def mysplit(s,dt): # s是字符串, dt分割符 res = [s] for d in dt: t = [] #map(lambda x: t.extend(x.split(d)),res) for x in res: l = x.split(d) t.extend(l) res = t return res s = "ad;s.de|djf|de,deff,tsrggv" l = mysplit(s,';.|,') print(l) # 方法二采用re来分割 import re l2 = re.split(r'[;.|,]+',s) # 对分割符匹配 print(l2)
如何判断字符串的开头或结尾
使用字符串的startwith() 与endwith() 方法来解决
如何进行字符串的拼接?
采用 + 来进行拼接, 或采用str.join()
如何对字符串进行左右居中对齐?
使用字符串的ljust() rjust() center() 方法进行对齐
使用format() 方法
s = "asbc" s.ljust(20) # 宽度20左对齐 s.rjust(20,"+") # 宽度20,右对齐 s.center(20) # format() <20 左对齐, >20 右对齐 ^20 居中 format(s,"<20")
去掉不需要的字符
1 strip() : 去掉两端的字符
2 采用replace() 的替换方法可以将其字符删除 如 s.replace('\t',' ')
3 当有多个需要去掉的字符,可以采用正在表达式re.sub() 如 re.sub('[\t\r]',' ', s) 将字符串s中的\t \r 字符替换为空
4 使用translate() 方法

浙公网安备 33010602011771号