本帖最后由 素简生香 于 2017-11-17 11:20 编辑
python 字符串处理函数(一) string = 'hellO BoWeiFeng' # 0. 字串长度:len(string) print '%s length=%d' % (string,len(string)) # 1. 字母处理: # 全部大写:string.upper() # 全部小写:string.lower() # 大小写互换:string.swapcase() # 首字母大写,其余小写:string.capitalize() 或 string.title() print '%s lower=%s' % (string,string.lower()) print '%s upper=%s' % (string,string.upper()) print '%s swapcase=%s' % (string,string.swapcase()) print '%s capitalize=%s' % (string,string.capitalize()) print '%s title=%s' % (string,string.title()) # 2. 格式化输出: # 根据 width长度,右对齐,左边不够用空格补齐:string.ljust(width) # 根据 width长度,左对齐,右边不够用空格补齐:string.rjust(width) # 根据 width长度,中间对齐,两边不够用空格补齐:string.center(width) # 根据 width长度,右对齐,左边不足用0补齐:string.zfill(width) print '%s ljust=%s' % (string,string.ljust(20)) print '%s rjust=%s' % (string,string.rjust(20)) print '%s center=%s' % (string,string.center(20)) print '%s zfill=%s' % (string,string.zfill(20))
|