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

กลับลำดับคำในสตริง (Reverse Words) ใน Python

เรามีสตริง และต้องการกลับลำดับคำ (Words) ในสตริง ใช้ split() และ reversed()

ตัวอย่าง

Input: "I am a python programmer"
Output: "programmer python a am I"

Input: "tutorialspoint is a educational website"
Output: "website educational a is tutorialspoint"

อัลกอริทึม

1. กำหนดสตริง
2. split() แยกคำด้วยช่องว่าง → list
3. reversed() กลับลำดับ list
4. join() รวมคำกลับเป็นสตริง
5. พิมพ์ผลลัพธ์

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

string = "I am a python programmer"

words = string.split()
words = list(reversed(words))
print(" ".join(words))

ผลลัพธ์

programmer python a am I

ตัวอย่างที่ 2

string = "tutorialspoint is a educational website"

words = string.split()
words = list(reversed(words))
print(" ".join(words))

ผลลัพธ์

website educational a is tutorialspoint

One-liner Version

print(" ".join(reversed(string.split())))

สรุป

split() → reversed() → join() เป็นรูปแบบทั่วไปสำหรับกลับลำดับคำในสตริง สั้นและอ่านง่าย หากมีข้อสงสัย สามารถถามได้ในส่วนความคิดเห็น