Python - 扩展字符频率字符串
给定一个字符串,其后字符的频率,创建适当的字符串。
例子:
Input : test_str = ‘g7f2g3i2s2b3e4’
Output : gggggggffgggiissbbbeeee
Explanation : g is succeeded by 7 and repeated 7 times.
Input : test_str = ‘g1f1g1’
Output : gfg
Explanation : f is succeeded by 1 and repeated 1 time.
方法一:使用zip() + join()
这是可以执行此任务的方法之一。其中,加入适当字符的任务是使用 join() 完成的, 字符串。缺点是字符的频率仅限于此中的一位数字。
Python3
# Python3 code to demonstrate working of
# Expand Character Frequency String
# Using join() + zip()
import re
# initializing string
test_str = 'g7f2g3i2s2b3e4s5t6'
# printing original string
print("The original string is : " + str(test_str))
# using zip() to pair up numbers and characters
# seperately
res = "".join(a *int(b) for a, b in zip(test_str[0::2], test_str[1::2]))
# printing result
print("The expanded string : " + str(res))
Python3
# Python3 code to demonstrate working of
# Expand Character Frequency String
# Using regex() + join()
import re
# initializing string
test_str = 'g7f2g3i2s2b3e4s5t10'
# printing original string
print("The original string is : " + str(test_str))
# using findall to pair up numbers and characters
# seperately, can include longer digit strings
res = ''.join(chr * int(num or 1)
for chr, num in re.findall(r'(\w)(\d+)?', test_str))
# printing result
print("The expanded string : " + str(res))
输出
The original string is : g7f2g3i2s2b3e4s5t6
The expanded string : gggggggffgggiissbbbeeeessssstttttt
方法 #2:使用 regex() + join()
这是可以执行此任务的另一种方式。在这个将数字和字符与不同字符串配对的任务中,使用 regex() 执行,优点是它可以接受数字大于 2 的数字。
蟒蛇3
# Python3 code to demonstrate working of
# Expand Character Frequency String
# Using regex() + join()
import re
# initializing string
test_str = 'g7f2g3i2s2b3e4s5t10'
# printing original string
print("The original string is : " + str(test_str))
# using findall to pair up numbers and characters
# seperately, can include longer digit strings
res = ''.join(chr * int(num or 1)
for chr, num in re.findall(r'(\w)(\d+)?', test_str))
# printing result
print("The expanded string : " + str(res))
输出
The original string is : g7f2g3i2s2b3e4s5t10
The expanded string : gggggggffgggiissbbbeeeessssstttttttttt