📝 Basic Python: Make the String Beautiful with f-String! 🌟
After we learned String Concatenation with a + sign, today I propose a much more modern and easy way to insert variable values into String, which is f-Strings! ✨
F-String stands for Formatted String Literal is the best way to Format String since Python 3.6.
💡 Simple f-String Method:
1. Prefixed with f: The first thing we need to do is put the letter f or F in front of the quotation mark (Single Quote 'or Double Quote') of the String, such as f. ".."
2.Use {} as a Placeholder: Where we want to insert a variable or result from a calculation, let us put that in the brace {}!
F-String is very useful because it makes our code easier to read (Readable) and type less than connecting a String with a + sign!
Try to use it and be comfortable with the f-String! Keep going. 🥰
f-String หรือ Formatted String Literal คือฟีเจอร์ที่เปิดตัวใน Python 3.6 ซึ่งช่วยให้การจัดการข้อความในโปรแกรมง่ายและสวยงามกว่าการต่อ String แบบเดิม โดยการเติม f หรือ F หน้าเครื่องหมายคำพูด จากนั้นใช้วงเล็บปีกกา {} เพื่อบรรจุค่าตัวแปรหรือ expression ต่าง ๆ ที่ต้องการแทรกลงในข้อความได้ทันที ตัวอย่างการใช้งานที่นิยมคือ ```python age = 36 txt = f"My name is John, I am {age}" print(txt) ``` ผลลัพธ์จะเป็นข้อความที่แทรกอายุลงไปอย่างตรงตัว ช่วยให้โค้ดดูสะอาดและเข้าใจง่ายกว่าการใช้ + เชื่อมต่อ String หลายชิ้น นอกจากนี้ ระบบ Placeholder ยังรองรับการใส่ expression หรือฟังก์ชัน รวมถึงรูปแบบการจัดรูปแบบค่าตัวแปรอย่างละเอียด เช่น การกำหนดจำนวนทศนิยม การเติมศูนย์ หรือการจัดรูปแบบวันที่ ตัวอย่าง ```python price = 59 txt = f"The price is {price} dollars" print(txt) ``` หรือใช้การ format ขั้นสูง เช่น ```python from datetime import datetime date = datetime.now() txt = f"Today is {date:%d-%m-%Y}" print(txt) ``` ข้อดีอีกประการของ f-String คือประสิทธิภาพที่สูงกว่าเมื่อเทียบกับวิธีอื่น ๆ ทำให้เหมาะกับทั้งโปรเจกต์ขนาดเล็กและใหญ่ สำหรับผู้เริ่มต้นเรียน Python การเข้าใจและเริ่มใช้ f-String จะช่วยลดความซับซ้อนของโค้ด ทำให้เขียนโค้ดได้เร็วขึ้นและบำรุงรักษาง่าย เหมาะสำหรับงานที่เกี่ยวข้องกับการแสดงผลข้อความ เช่น การสร้างรายงาน แสดงผลข้อมูล หรือการเขียนโปรแกรมที่ต้องจัดการข้อความบ่อย ๆ สรุปง่าย ๆ f-String คือเครื่องมือขั้นเทพที่พัฒนาให้ Python เจ๋งขึ้นทั้งเรื่องประสิทธิภาพและความง่ายในการเขียนโค้ดนั่นเอง ลองนำไปประยุกต์ใช้ในการเขียนโปรแกรมของคุณ รับรองว่าจะช่วยให้การจัดการ String สนุกและมีประสิทธิภาพมากขึ้นแน่นอน!

