【问题标题】:Add string in a certain interval position in Python在Python中的某个间隔位置添加字符串
【发布时间】:2019-05-29 21:14:15
【问题描述】:

我有这样的字符串718868538ddwe。我想以 3 的间隔插入反斜杠 ("\")。

我需要这样的输出:718\868\538\ddw\e。

【问题讨论】:

    标签: python string python-2.7 list


    【解决方案1】:

    您可以将str.join 与列表理解一起使用:

    x = '718868538ddwe'
    res = '\\'.join([x[3*i: 3*(i+1)] for i in range(len(x) // 3 + 1)])
    
    print(res)
    # 718\868\538\ddw\e
    

    【讨论】:

      【解决方案2】:
      def chunks(input_str):
          current = input_str
          while current:
              next, current = current[:3], current[3:]
              yield next
      
      str = ''.join([chunk + '/' for chunk in chunks(input_str)]) 
      

      【讨论】:

      • li = textwrap.wrap(dst,3)
      猜你喜欢
      • 2011-07-12
      • 1970-01-01
      • 1970-01-01
      • 2021-07-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-04
      • 2021-07-14
      • 2019-10-29
      相关资源
      最近更新 更多