【问题标题】:How to increment string value in Python [closed]如何在Python中增加字符串值[关闭]
【发布时间】:2023-03-03 10:46:01
【问题描述】:

如何在 Python 中增加字符串?

我有以下字符串:str = 'tt0000002' 我想使用循环将此字符串增加到'tt0000003', 'tt0000004','tt0000005' (...) to 'tt0010000'

我该怎么做?

【问题讨论】:

    标签: python string for-loop while-loop


    【解决方案1】:

    一种不太优雅的方式是:

    def increment_string(string, num_chars, numbers):
        return [f'{string}{str(0) * (num_chars-len(str(i)))}' + str(i) for i in numbers]
            
    increment_string(string = 'tt', num_chars = 8, numbers = [1,10,50,100,1000,100000,1000000,1000000,10000000])
    
    

    【讨论】:

      【解决方案2】:
      #ugly code but works
      
      s='tt0000002'
      
      for k in range(100): #increase the range 
          print(s)
          n=int(s[2:])
          n_s=str(n+1)
          l=len(n_s)
      
          temp='tt'
          for z in range(0,7-l):
              temp+='0'
              s=temp+n_s
      

      【讨论】:

      • 虽然此代码 sn-p 可能是解决方案,但 including an explanation 确实有助于提高您的帖子质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
      【解决方案3】:

      你可以直接生成id:

      此处的示例值在 2 到 100 之间,增量为 10:

      ids = [f'tt{i:07d}' for i in range(2, 100, 10)]
      

      输出:

      ['tt0000002',
       'tt0000012',
       'tt0000022',
       'tt0000032',
       'tt0000042',
       'tt0000052',
       'tt0000062',
       'tt0000072',
       'tt0000082',
       'tt0000092']
      

      如果你真的需要从你的字符串中增加:

      def increment(s):
          # splitting here after 2 characters, but this could use a regex
          # or any other method if the identifier is more complex
          return f'{s[:2]}{int(s[2:])+1:07d}'
      

      示例:

      >>> mystr = 'tt0000002'
      >>> increment(mystr)
      'tt0000003'
      

      编辑

      这是一个“更智能”的版本,它应该适用于任何 'XXX0000' 形式的 id:

      def increment(s):
          import re
          try:
              a, b = re.match('(\D*)(\d+)', s).groups()
          except (AttributeError, IndexError):
              print('invalid id')
              return 
          return f'{a}{int(b)+1:0{len(b)}d}'
      

      例子:

      >>> increment('tt0000002')
      'tt0000003'
      >>> increment('abc1')
      'abc2'
      >>> increment('abc999')
      'abc1000'
      >>> increment('0000001')
      '0000002'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-09
        • 1970-01-01
        • 1970-01-01
        • 2016-08-27
        • 2021-07-17
        • 2014-07-10
        相关资源
        最近更新 更多