Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!
This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join 11 million other learners and get started learning Python for data science today!
Good news! You can save 25% off your Datacamp annual subscription with the code LEARNPYTHON23ALE25 - Click here to redeem your discount
การจัดรูปแบบสตริง
Python ใช้การจัดรูปแบบสไตล์ C เพื่อสร้างสตริงใหม่ที่มีรูปแบบ โดยที่ดำเนินการ "%" ถูกใช้สำหรับการจัดรูปแบบเซ็ทของตัวแปรที่รวมอยู่ใน "tuple" (รายการขนาดคงที่) พร้อมกับรูปแบบของสตริง ซึ่งประกอบด้วยข้อความปกติพร้อมกับ "argument specifiers" สัญลักษณ์พิเศษเช่น "%s" และ "%d"
สมมติว่าคุณมีตัวแปรชื่อ "name" ที่มีชื่อผู้ใช้ของคุณอยู่ในนั้น และคุณต้องการแสดงคำทักทายไปยังผู้ใช้นั้น
# This prints out "Hello, John!"
name = "John"
print("Hello, %s!" % name)
ในการใช้ argument specifier สองตัวขึ้นไป ให้ใช้ tuple (วงเล็บ):
# This prints out "John is 23 years old."
name = "John"
age = 23
print("%s is %d years old." % (name, age))
วัตถุใด ๆ ที่ไม่ใช่สตริงก็สามารถจัดรูปแบบได้โดยใช้ตัวดำเนินการ %s เช่นกัน สตริงที่ส่งคืนจากเมธอด "repr" ของวัตถุนั้นจะถูกจัดรูปแบบเป็นสตริง ตัวอย่างเช่น:
# This prints out: A list: [1, 2, 3]
mylist = [1,2,3]
print("A list: %s" % mylist)
นี่คือตัวกำหนดอาร์กิวเมนต์พื้นฐานบางอย่างที่คุณควรรู้:
%s - สตริง (หรือวัตถุใด ๆ ที่มีการแสดงเป็นสตริง เช่น ตัวเลข)
%d - จำนวนเต็ม
%f - จำนวนเลขทศนิยม
%.<จำนวนหลัก>f - จำนวนเลขทศนิยมที่มีจำนวนหลักคงที่ทางด้านขวาของจุด
%x/%X - จำนวนเต็มในรูปแบบเลขฐานสิบหก (ตัวพิมพ์เล็ก/ตัวพิมพ์ใหญ่)
Exercise
คุณจะต้องเขียนสตริงรูปแบบที่พิมพ์ข้อมูลออกโดยใช้ไวยากรณ์ต่อไปนี้:
Hello John Doe. Your current balance is $53.44.
data = ("John", "Doe", 53.44)
format_string = "Hello"
print(format_string % data)
data = ("John", "Doe", 53.44)
format_string = "Hello %s %s. Your current balance is $%s."
print(format_string % data)
#test_output_contains("Hello John Doe. Your current balance is $53.44.", no_output_msg= "Make sure you add the `%s` in the correct spaces to the `format_string` to meeet the exercise goals!")
test_object('format_string')
success_msg('Great work!')
This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!