字符串的处理

字符串的处理

  1. 保留两位小数 推荐 format
    demo = 20.30
    print('这是format的方式:{:.2f}'.format(demo))   # 这是format的方式:20.30 
    print('这是的%%方式:%.2f' % demo)  # 这是的%方式:20.30  note:注意%的是使用
    print('不建议使用round函数:{}'.format(round(demo, 2)))  # 不建议使用round函数:20.3
    
  2. 填充 结果类型均为:str
    • 方法一

      '789'.ljust(10, '0')  # 7890000000
      '789'.rjust(10, '0')  # 0000000789
      
    • 方法二

      '789'.zfill(10)   # 0000000789
      
    • 方法三

      '%010d' % 789   # 0000000789
      
  3. 字符串的替换
    • 方式一:sub re.sub 会得到一个替换后的新的字符串,原本字符串保持不变

      demo = 'xcopy /s "C:\program files" "d:\\"'
      
      # 这一步会将得到的新字符串进行处理   re.sub(旧, 新, 待处理的目标)
      ret = re.sub(r'"(.*?)"', '', demo)
      # ret 结果: xcopy /s 
      
posted @ 2022-02-21 14:31  疯狂列表推导式  阅读(30)  评论(0编辑  收藏  举报