Python – 在每个重复字符串的每隔 K 个元素后插入字符


当需要在每个重复字符串的每隔“K”个元素后插入字符时,会定义一个使用“append”方法、连接运算符和列表切片的方法。

示例

以下是相同内容的演示 -

Open Compiler
def insert_char_after_key_elem(my_string, my_key, my_char): my_result = [] for index in range(0, len(my_string), my_key): my_result.append(my_string[:index] + my_char + my_string[index:]) return str(my_result) my_string = 'PythonToCode' print("The string is :") print(my_string) K = 2 print("The value of K is ") print(K) add_char = ";" print("The result is :") print(insert_char_after_key_elem(my_string, K, add_char))

输出

The string is :
PythonToCode
The value of K is
2
The result is :
[';PythonToCode', 'Py;thonToCode', 'Pyth;onToCode', 'Python;ToCode', 'PythonTo;Code',
'PythonToCo;de']

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

解释

  • 定义了一个名为“insert_char_after_key_elem”的方法,该方法将字符串、键和字符作为参数。

  • 定义了一个空列表。

  • 迭代作为参数传递的字符串和键。

  • 使用列表切片和连接运算符“+”将输出追加到空列表。

  • 将其转换为字符串并显示为方法的输出

  • 在方法外部,定义一个字符串,并在控制台上显示。

  • 定义“键”值和“字符”值。

  • 通过传递所需参数来调用该方法。

  • 在控制台上显示输出。

更新于: 2021年9月8日

170 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告