Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรม Python ลบตัวอักษรที่ Index ที่กำหนดออกจากสตริง


เมื่อต้องการลบตัวอักษรที่ตำแหน่ง index เฉพาะจากสตริง ให้วนลูปสร้างสตริงใหม่โดยข้าม index นั้น

ตัวอย่างโค้ด

my_string = "Hi there how are you"
print("The string is:", my_string)

index_to_remove = 2
new_string = ''

for i in range(len(my_string)):
    if i != index_to_remove:
        new_string += my_string[i]

print(f"String after removing index {index_to_remove}:")
print(new_string)

ผลลัพธ์

The string is: Hi there how are you
String after removing index 2: Hithere how are you

คำอธิบาย

  • index 2 คือตัวอักษรที่ 3 (0-based) คือ ' ' (space) หลัง 'Hi'

  • วนลูปด้วย range(len(my_string)) ได้ index ทั้งหมด

  • ถ้า index ไม่ตรงกับที่ต้องการลบ ให้ต่อตัวอักษรเข้า new_string

  • วิธีง่ายกว่า: my_string[:index] + my_string[index+1:] (slicing)