ประเภทการแปลง เป็นบางครั้งที่จำเป็นเมื่อผู้ใช้ต้องการแปลงข้อมูลประเภทหนึ่งเป็นข้อมูลประเภทอื่นตามความต้องการ
Python มีฟังก์ชันในตัว str() เพื่อแปลงจำนวนเต็มเป็นสตริง เราจะพูดถึงวิธีการอื่นๆ นอกเหนือจากนี้เพื่อแปลง int เป็นสตริงใน Python
ใช้ str()
นี่เป็นวิธีการที่ใช้บ่อยที่สุดในการแปลง int เป็นสตริงใน Python str() ใช้ตัวแปรจำนวนเต็มเป็นพารามิเตอร์และแปลงเป็นสตริง
ไวยากรณ์
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 <class 'int'> 2 Datatype after conversion <class 'str'>
ประเภท() ฟังก์ชั่นให้ประเภทข้อมูลของตัวแปรที่ส่งผ่านเป็นพารามิเตอร์
ในโค้ดด้านบน ก่อนการแปลง ประเภทข้อมูลของ num เป็น int และหลังการแปลง ประเภทข้อมูลของ num คือ str(เช่น string ใน python)
การใช้เอฟสตริง
ไวยากรณ์
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 <class 'int'> 2 Datatype after conversion <class 'str'>
การใช้คีย์เวิร์ด “%s”
ไวยากรณ์
“%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 <class 'int'> 2 Datatype after conversion <class 'str'>
การใช้ฟังก์ชัน .format()
ไวยากรณ์
‘{}’.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 <class 'int'> 2 Datatype after conversion <class 'str'>
นี่เป็นวิธีการบางส่วนในการแปลง int เป็นสตริงใน Python เราอาจจำเป็นต้องแปลง int เป็นสตริงในบางสถานการณ์ เช่น การผนวกค่าที่เก็บไว้ใน int เป็นตัวแปรสตริงบางตัว สถานการณ์ทั่วไปอย่างหนึ่งคือการกลับค่าจำนวนเต็ม เราอาจแปลงเป็นสตริงแล้วย้อนกลับซึ่งง่ายกว่าการใช้ตรรกะทางคณิตศาสตร์เพื่อย้อนกลับจำนวนเต็ม