我正在寻找一种漂亮,高效和pythonic的方式来做这样的事情:
('zone1', 'pcomp110007')
对此:
'ZONE 1, PCOMP 110007'
regex如果可能的话,不使用(除非它确实产生了很大的不同......).因此,将每个字母转换为大写字母,在字母和数字之间放置一个空格,并用逗号连接.
我写的是以下内容:
tags = ('zone1', 'pcomp110007')
def sep(astr):
chars = ''.join([x.upper() for x in astr if x.isalpha()])
nums = ''.join([x for x in astr if x.isnumeric()])
return chars + ' ' + nums
print(', '.join(map(sep, tags)))
Run Code Online (Sandbox Code Playgroud)
哪个确实产生了预期的结果,但看起来有点太多了.
元组的长度可能不同,但数字总是在每个字符串的末尾.
正则表达式确实有帮助.这应该总是有效:
import re
tags = ('zone1', 'pcomp110007')
def sep(s):
word = re.split(r'\d', s)[0]
return word.upper() + " " + s[len(word):]
print(', '.join(map(sep, tags)))
Run Code Online (Sandbox Code Playgroud)
我的想法:
保留sep原始代码中的正常功能,以提高可读性/维护性,但也可以re按照 Abdou 的答案中的建议进行利用。
import re
tags = ('zone1', 'pcomp110007')
def sep(astr):
alpha, num = re.match('([^\d]+)([\d]+)', astr).groups()
return '{} {}'.format(alpha.upper(), num)
print(', '.join(map(sep, tags)))
Run Code Online (Sandbox Code Playgroud)
编辑:请注意,如果您愿意,我认为返回也是合理的:
return alpha.upper() + ' ' + num
Run Code Online (Sandbox Code Playgroud)
或旧式字符串格式:
return '%s %s' %(alpha.upper(), num)
Run Code Online (Sandbox Code Playgroud)
无论您最舒服什么。