我有以下字符串,我将其拆分:
>>> st = '%2g%k%3p'
>>> l = filter(None, st.split('%'))
>>> print l
['2g', 'k', '3p']
现在我想打印 g 字母两次,k 字母一次,p 字母 3 次:
ggkppp
这怎么可能?
最佳答案
您可以使用 generator
与 isdigit()
检查您的第一个符号是否为数字,然后返回具有适当计数的以下字符串。然后你可以使用 join
得到你的输出:
''.join(i[1:]*int(i[0]) if i[0].isdigit() else i for i in l)
演示:
In [70]: [i[1:]*int(i[0]) if i[0].isdigit() else i for i in l ]
Out[70]: ['gg', 'k', 'ppp']
In [71]: ''.join(i[1:]*int(i[0]) if i[0].isdigit() else i for i in l)
Out[71]: 'ggkppp'
编辑
使用 re
第一个数字为多位时的模块:
''.join(re.search('(\d+)(\w+)', i).group(2)*int(re.search('(\d+)(\w+)', i).group(1)) if re.search('(\d+)(\w+)', i) else i for i in l)
例子:
In [144]: l = ['12g', '2kd', 'h', '3p']
In [145]: ''.join(re.search('(\d+)(\w+)', i).group(2)*int(re.search('(\d+)(\w+)', i).group(1)) if re.search('(\d+)(\w+)', i) else i for i in l)
Out[145]: 'ggggggggggggkdkdhppp'
EDIT2
对于您的输入,例如:
st = '%2g_%3k%3p'
您可以替换 _
使用空字符串,然后添加 _
如果列表中的作品以 _
结尾,则到最后符号:
st = '%2g_%3k%3p'
l = list(filter(None, st.split('%')))
''.join((re.search('(\d+)(\w+)', i).group(2)*int(re.search('(\d+)(\w+)', i).group(1))).replace("_", "") + '_' * i.endswith('_') if re.search('(\d+)(\w+)', i) else i for i in l)
输出:
'gg_kkkppp'
EDIT3
没有 re
的解决方案模块,但通常循环工作 2 位数。你可以定义函数:
def add_str(ind, st):
if not st.endswith('_'):
return st[ind:] * int(st[:ind])
else:
return st[ind:-1] * int(st[:ind]) + '_'
def collect(l):
final_str = ''
for i in l:
if i[0].isdigit():
if i[1].isdigit():
final_str += add_str(2, i)
else:
final_str += add_str(1, i)
else:
final_str += i
return final_str
然后将它们用作:
l = ['12g_', '3k', '3p']
print(collect(l))
gggggggggggg_kkkppp
关于python - 在 Python 中以特定模式打印字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35266225/