📜  Python - 在字符串中自定义连续字符重复

📅  最后修改于: 2022-05-13 01:54:27.022000             🧑  作者: Mango

Python - 在字符串中自定义连续字符重复

给定一个字符串,按字典中映射的数字连续重复字符。

方法#1:使用循环

这是可以执行此任务的方法之一。在此,我们遍历每个字符并检查映射其重复并重复该数量。

Python3
# Python3 code to demonstrate working of 
# Custom Consecutive character repetition in String
# Using loop
  
# initializing string
test_str = 'Geeks4Geeks'
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing dictionary 
test_dict = {"G" : 3, "e" : 2, "4" : 4, "k" : 5, "s" : 3}
  
res = ""
for ele in test_str:
      
    # using * operator for repetition
    # using + for concatenation
    res += ele * test_dict[ele]
  
# printing result 
print("The filtered string : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Custom Consecutive character repetition in String
# Using list comprehension + join()
  
# initializing string
test_str = 'Geeks4Geeks'
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing dictionary 
test_dict = {"G" : 3, "e" : 2, "4" : 4, "k" : 5, "s" : 3}
  
# using join to perform concatenation of strings
res = "".join([ele * test_dict[ele] for ele in test_str])
  
# printing result 
print("The filtered string : " + str(res))


输出
The original string is : Geeks4Geeks
The filtered string : GGGeeeekkkkksss4444GGGeeeekkkkksss

方法 #2:使用列表理解 + join()

这是可以执行此任务的另一种方式。在此,我们执行与上述函数类似的任务。唯一的区别是我们使用 join() 来合并创建的重复列表。

蟒蛇3

# Python3 code to demonstrate working of 
# Custom Consecutive character repetition in String
# Using list comprehension + join()
  
# initializing string
test_str = 'Geeks4Geeks'
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing dictionary 
test_dict = {"G" : 3, "e" : 2, "4" : 4, "k" : 5, "s" : 3}
  
# using join to perform concatenation of strings
res = "".join([ele * test_dict[ele] for ele in test_str])
  
# printing result 
print("The filtered string : " + str(res)) 
输出
The original string is : Geeks4Geeks
The filtered string : GGGeeeekkkkksss4444GGGeeeekkkkksss