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

Python: ลบตัวอักษรสุดท้ายจาก String (Remove Last Character)

Strings เป็น iterable objects เข้าถึงค่าได้ด้วย indexing และ slicing เทคนิคเหล่านี้ดึง individual character หรือ range of characters จาก string ได้

คู่มือนี้อธิบายวิธีลบตัวอักษรสุดท้ายจาก Python string พร้อมตัวอย่าง ช่วยให้คุณทำได้ในโค้ดของตัวเอง

Python: ลบตัวอักษรสุดท้ายจาก String

สร้างโปรแกรมลบตัวอักษรสุดท้ายจาก employee identifier ตัวอักษรนี้บอกว่าแผนกไหน เช่น "M" = marketing department จะลบตัวอักษรนี้เพราะจะแทนที่ด้วยระบบใหม่ติดตามแผนก

เริ่มถามผู้ใช้ employee identifier ด้วย input():

identifier = input("What is the employee's identifier? ")

ลบตัวอักษรสุดท้ายจาก identifier:

new_identifier = identifier[:-1]

[::-1] คือ string slice operation ลบตัวอักษรสุดท้าย ใช้ negative indexing ดึง items จากท้าย string แสดง employee's new identifier คอนโซล:

print("The employee's new identifier is {}.".format(new_identifier))

.format() statement แทนที่ curly braces ใน string ด้วย employee's new identifier รันโค้ด:

What is the employee's identifier? 28371M
The employee's new identifier is 28371.

โปรแกรมลบค่าสุดท้ายใน employee's identifier สำเร็จ

ยังไม่จบ หากผู้ใช้ใส่ค่าว่าง โปรแกรมคืนค่า:

The employee's new identifier is .

ควรทำให้ graceful มากขึ้น ต้อง slice employee's identifier ก็ต่อเมื่อ identifier มีมากกว่า 2 characters ไม่เช่นนั้น บอกผู้ใช้ใส่ valid identifier

กำหนด "if" statement เช็คความยาว identifier:

identifier = input("What is the employee's identifier? ")
if len(identifier) > 1:
    new_identifier = identifier[:-1]
    print("The employee's new identifier is {}.".format(new_identifier))
else:
    print("Please insert a valid identifier.")

ใช้ len() method หาความยาว employee's identifier ถ้าความยาวมากกว่า "1" if statement รัน ไม่งั้น else statement รัน

รัน Python program ใส่ identifier น้อยกว่า 2 ตัวอักษร:

What is the employee's identifier? B
Please insert a valid identifier.

โค้ดบอกว่าต้องใส่ valid identifier

สรุป

Slicing syntax ให้ลบตัวอักษรสุดท้ายจาก string object ใน Python ได้ แค่ระบุ string และเพิ่ม [:-1] หลัง string ตอนนี้คุณพร้อมลบตัวอักษรสุดท้ายจาก Python string อย่าง expert แล้ว!