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

ตัวดำเนินการ % ทำอะไรกับสตริงใน Python

% เป็นตัวดำเนินการจัดรูปแบบสตริง (string formatting operator) หรือ interpolation operator กำหนด format % values (โดย format เป็นสตริง) ตัวกำหนดการแปลง (conversion specifications) ใน format จะถูกแทนที่ด้วยองค์ประกอบศูนย์หรือมากกว่าของ values ผลลัพธ์คล้ายกับการใช้ sprintf() ในภาษา C ตัวอย่าง:

>>> lang = "Python"
>>> print("%s is awesome!" % lang)
Python is awesome!

ยังสามารถจัดรูปแบบตัวเลขได้ด้วยสัญกรณ์นี้ ตัวอย่าง:

>>> cost = 128.527
>>> print("The book costs $%.2f at the bookstore" % cost)
The book costs $128.53 at the bookstore

ยังสามารถใช้ดิกชันนารีในการ interpolate สตริงได้ มีไวยากรณ์ที่ต้องระบุคีย์ในวงเล็บระหว่าง % และตัวอักษรการแปลง ตัวอย่าง:

print('%(language)s has %(number)03d quote types.' % {'language': "Python", "number": 2})
Python has 002 quote types.

อ่านเพิ่มเติมเกี่ยวกับการจัดรูปแบบสตริงและตัวดำเนินการได้ที่: https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting