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

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


สตริงคืออาร์เรย์ของตัวอักษร เริ่มดัชนีที่ 0 สามารถลบตัวอักษรที่ตำแหน่ง n ได้โดยแยกเป็นสองส่วนแล้วรวมกัน

ตัวอย่าง

Input: python, n=3
Output: pyton

อัลกอริทึม

  1. รับสตริงเข้า
  2. รับดัชนี n ที่ต้องการลบ
  3. เก็บตัวอักษรก่อน n ไว้ใน X
  4. เก็บตัวอักษรหลัง n ไว้ใน Y
  5. คืนค่า X + Y

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

def removechar(str1, n):
    x = str1[:n]
    y = str1[n+1:]
    return x + y

if __name__ == '__main__':
    str1 = input("Enter a string: ")
    n = int(input("Enter the n-th index: "))
    print("The new string is:")
    print(removechar(str1, n))

ผลลัพธ์

Enter a string: python
Enter the n-th index: 3
The new string is:
pyton