简体   繁体   English

Python脚本用连续整数替换字符串中的字符?

[英]Python script to replace characters in string with sequential integers?

I would like to create a script in Python to do the following: 我想在Python中创建一个脚本来执行以下操作:

take multiple lines of text: 接受多行文字:

&asdf01&  
&asdf01&  
&asdf01&  
&asdf01&  
&asdf01&  
&asdf01&  
&asdf01&  
&asdf01&  
&asdf01&  
&asdf01&  
&asdf01&

and replace as follows: 并替换如下:

&asdf01&  
&asdf02&  
&asdf03&  
&asdf04&  
&asdf05&  
&asdf06&  
&asdf07&  
&asdf08&  
&asdf09&  
&asdf10&  
&asdf11&

Basically I need to replace consecutive characters in a string with a numerical value based off the line number of the string. 基本上,我需要根据字符串的行号用数值替换字符串中的连续字符。

Any help is greatly appreciated. 任何帮助是极大的赞赏。

This code should help you. 此代码应为您提供帮助。

 strings = ['&asdf01&',  
'&asdf01&',  
'&asdf01&',  
'&asdf01&',  
'&asdf01&',  
'&asdf01&',  
'&asdf01&',  
'&asdf01&',  
'&asdf01&',
'&asdf01&', 
'&asdf01&'
]

for i, element in zip(range(1, len(strings)+1), strings):
    element = list(element)
    if i<10:
        element[-3] = '0'
    else:
        element[-3] = ''
    element[-2] = str(i)
    element = ''.join(element)
    strings[i-1] = element

print(strings)

Output: 输出:

['&asdf01&', '&asdf02&', '&asdf03&', '&asdf04&', '&asdf05&', '&asdf06&', '&asdf07&', '&asdf08&', '&asdf09&', '&asdf10&', '&asdf11&'] ['&asdf01&','&asdf02&','&asdf03&','&asdf04&','&asdf05&','&asdf06&','&asdf07&','&asdf08&','&asdf09&','&asdf10&','&asdf11

It depends a little on what exactly you want to increment. 这取决于您要增加的精确度。 Should it work for arbitrary structured input strings or can we assume to always have the pattern &asdf01& ?. 它应该适用于任意结构化的输入字符串,还是可以假定始终使用模式&asdf01& ?。

This piece of code is kind of flexible and would increment the first 2 digits it does find in a string: 这段代码有点灵活,可以增加它在字符串中找到的前两位数字:

import re

def increment_digits(input_string):

  pattern = r'(\d{2})'
  match = re.search(pattern, input_string)

  if match:

    digits = match.group(1)
    increment = int(digits) + 1 
    zero_padded_increment = "{:02d}".format(increment)

    s = match.start(1)
    e = match.end(1)

    composed_string = input_string[:s] + zero_padded_increment + input_string[e:]
    return composed_string

  else:

    return input_string

in_list = [
  'Ihave20apples',
  'Ilike452people',
  'With99dollarsIbuy20iphones',
  '88abc99def0123xyz',
  '43',
  '0',
  'Hello',
  '&asdf01&']

for i in in_list:
  o = increment_digits(i)
  print("{:25s} -> {:25s}".format(i, o))

Result: 结果:

Ihave20apples             -> Ihave21apples
Ilike452people            -> Ilike462people
With99dollarsIbuy20iphones -> With100dollarsIbuy20iphones
88abc99def0123xyz         -> 89abc99def0123xyz
43                        -> 44
0                         -> 0
Hello                     -> Hello
&asdf01&                  -> &asdf02&

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM