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" ที่มีชื่อผู้ใช้ของคุณอยู่ในนั้น และคุณต้องการแสดงคำทักทายไปยังผู้ใช้นั้น
ในการใช้ argument specifier สองตัวขึ้นไป ให้ใช้ tuple (วงเล็บ):
วัตถุใด ๆ ที่ไม่ใช่สตริงก็สามารถจัดรูปแบบได้โดยใช้ตัวดำเนินการ %s เช่นกัน สตริงที่ส่งคืนจากเมธอด "repr" ของวัตถุนั้นจะถูกจัดรูปแบบเป็นสตริง ตัวอย่างเช่น:
นี่คือตัวกำหนดอาร์กิวเมนต์พื้นฐานบางอย่างที่คุณควรรู้:
%s - สตริง (หรือวัตถุใด ๆ ที่มีการแสดงเป็นสตริง เช่น ตัวเลข)
%d - จำนวนเต็ม
%f - จำนวนเลขทศนิยม
%.<จำนวนหลัก>f - จำนวนเลขทศนิยมที่มีจำนวนหลักคงที่ทางด้านขวาของจุด
%x/%X - จำนวนเต็มในรูปแบบเลขฐานสิบหก (ตัวพิมพ์เล็ก/ตัวพิมพ์ใหญ่)
Exercise
คุณจะต้องเขียนสตริงรูปแบบที่พิมพ์ข้อมูลออกโดยใช้ไวยากรณ์ต่อไปนี้:
Hello John Doe. Your current balance is $53.44.
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!
