เมื่อต้องการแทรกตัวอักษรในสตริงซ้ำทุก K ตัวอักษร สามารถใช้ฟังก์ชันที่มี append(), ตัวดำเนินการ + และ list slicing ได้
ตัวอย่าง
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']
คำอธิบาย
กำหนดฟังก์ชันรับสตริง, K (ช่วงแทรก), และตัวอักษรที่จะแทรก
สร้างลิสต์ว่าง วนลูปทุก K ตัวอักษร ตัดสตริงสองส่วน (
[:index]และ[index:]) แทรกตัวอักษรระหว่างกลางเพิ่มสตริงที่แทรกแล้วในลิสต์ แปลงลิสต์เป็นสตริงคืนค่า
เรียกใช้ฟังก์ชันแสดงผลลัพธ์