Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Chương trình Python xóa ký tự ở chỉ số lẻ trong chuỗi

Duyệt chuỗi, chỉ giữ lại ký tự tại index chẵn (0, 2, 4...), bỏ index lẻ.

Ví dụ

def remove_odd_indices(s):
    result = ""
    i = 0
    while i < len(s):
        if i % 2 == 1:
            i += 1
            continue
        result += s[i]
        i += 1
    return result

text = "Hi there Will"
print("Gốc:", text)
print("Sau khi xóa index lẻ:", remove_odd_indices(text))

Kết quả

Gốc: Hi there Will
Sau khi xóa index lẻ: H hr il

Giải thích

  • Index 0-based: index lẻ là 1, 3, 5... (ký tự thứ 2, 4, 6...).
  • Vòng lặp while, nếu i % 2 == 1 thì skip.
  • Kết quả: giữ index 0,2,4,6,8,10 -> 'H', ' ', 'h', 'r', ' ', 'i' -> "H hr il".
  • Pythonic hơn: s[::2] (slice step 2).