การแปลงชนิดข้อมูล (Type conversion) จำเป็นตอนที่ผู้ใช้ต้องการแปลงชนิดข้อมูลหนึ่งเป็นอีกชนิดหนึ่งตามความต้องการ
Python มีฟังก์ชันสำเร็จรูป str() สำหรับแปลงจำนวนเต็ม (integer) เป็นสตริง (string) เราจะพูดถึงวิธีการอื่นๆ เพิ่มเติมนอกเหนือจากนี้
การใช้ str()
นี่คือวิธีที่ใช้บ่อยที่สุดในการแปลง int เป็น string ใน Python ฟังก์ชัน str() จะรับตัวแปร integer เป็นพารามิเตอร์และแปลงเป็น string
รูปแบบ (Syntax)
str(integer_variable)
ตัวอย่าง
num = 2
print("Datatype before conversion", type(num))
num = str(num)
print(num)
print("Datatype after conversion", type(num))
ผลลัพธ์
Datatype before conversion
2
Datatype after conversion
ฟังก์ชัน type() ใช้แสดงชนิดข้อมูลของตัวแปรที่ส่งเข้ามาเป็นพารามิเตอร์
ในโค้ดข้างต้น ก่อนแปลง ชนิดข้อมูลของ num คือ int และหลังแปลงแล้ว ชนิดข้อมูลของ num คือ str (string ใน Python)
การใช้ f-string
รูปแบบ (Syntax)
f'{integer_variable}'
ตัวอย่าง
num = 2
print("Datatype before conversion", type(num))
num = f'{num}'
print(num)
print("Datatype after conversion", type(num))
ผลลัพธ์
Datatype before conversion
2
Datatype after conversion
การใช้คีย์เวิร์ด "%s"
รูปแบบ (Syntax)
"%s" % integer_variable
ตัวอย่าง
num = 2
print("Datatype before conversion", type(num))
num = "%s" % num
print(num)
print("Datatype after conversion", type(num))
ผลลัพธ์
Datatype before conversion
2
Datatype after conversion
การใช้ฟังก์ชัน .format()
รูปแบบ (Syntax)
'{}'.format(integer_variable)
ตัวอย่าง
num = 2
print("Datatype before conversion", type(num))
num = '{}'.format(num)
print(num)
print("Datatype after conversion", type(num))
ผลลัพธ์
Datatype before conversion
2
Datatype after conversion
นี่คือวิธีการบางส่วนในการแปลง int เป็น string ใน Python เราอาจต้องแปลง int เป็น string ในบางสถานการณ์ เช่น การนำค่าที่เก็บใน int ไปต่อท้ายกับตัวแปร string การกลับลำดับตัวเลข (reverse integer) เป็นตัวอย่างทั่วไป - เราสามารถแปลงเป็น string แล้วค่อยกลับลำดับ ซึ่งง่ายกว่าการใช้ตรรกะทางคณิตศาสตร์