你可以试试这样的方法:report_one = '00177 12345 24'
report_two = 'G0177 12345 24'
report_three = 'G0177 I2345 24'
def convert(original):
s = original.split()
for i in range(2): # 2 is used here because that's how many 'words'
try: # we want to check for numeric-ness. This can
int(s[i]) # be adjusted if you have to change your schema
except ValueError: # at some point in the future.
s[i] += 'S'
return ' '.join(s)
print convert(report_one) # Prints 00177 12345 24
print convert(report_two) # Prints G0177S 12345 24
print convert(report_three) # Prints G0177S I2345S 24
这首先将字符串拆分为单独的单词。您知道第一个和第二个可能是整数,您需要一种方法让下一个系统将它们理解为字符串。在
如果字符串不是整数,则使用拆分词将单词转换为try块下的int将抛出ValueError。也就是说,如果它包含任何字母,except ValueError子句将启动。此时,您可以简单地在末尾附加一个字母,然后让您的下一个系统扫描该单词的结尾字母(这里我的示例使用'S')。在
如果要在开头附加一个字母,可以将s[i] += 'S'替换为:s[i] = 'S' + s[i]