Devdit
 

แปลง String เป็น Int Python ด้วยคำสั่ง int

8.2K

สอนเขียนการแปลง string เป็น int ภาษา Python ด้วยคำสั่ง int สามารถเขียนโปรแกรมได้ดังนี้

 

ตัวอย่าง แปลง string เป็น int Python

a = '50'
b = 10
total = int(a) + b
print( total )

ผลลัพธ์

60

โค้ดด้านบนมี 2 ตัวแปร คือ ตัวแปร a เป็นข้อความ มีค่าเท่ากับ 50 และตัวแปร b มีค่าเท่ากับ 10 เป็นชนิดตัวเลข จากนั้นทำการแปลงตัวแปร a จาก string เป็น int ด้วยคำสั่ง int() และนำไปบวก และเก็บผลลัพธ์ไว้ที่ตัวแปร total พร้อมกับแสดงผลออกมาด้วยคำสั่ง print

 

ตัวอย่าง โปรแกรม Error กรณีไม่แปลงตัวแปร a ไปเป็น int

a = '50'
b = 10
total = a + b
print( total )

ผลลัพธ์

Traceback (most recent call last):
  File "D:\python\test.py", line 3, in <module>
    total = (a) + b
TypeError: can only concatenate str (not "int") to str
เขียน 2 ปีที่แล้ว
ชอบ
ลิ้งก์
แชร์
Devdit มีช่อง YouTube แล้ว
เราสร้างวิดีโอเกี่ยวกับเทคโนโลยี ทำตามง่ายๆ