python字符串中添加字符_分割用户输入并在Python字符串中添加字符

你可以试试这样的方法: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]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值