01 Python 기초 배우기 - (4) type_casting

처어리·2024년 1월 16일

python

목록 보기
5/36
post-thumbnail

04. type_casting

자료형( data type )

  • 데이터를 보관하는 공간의 형식을 정의합니다.
  • type()
    변수에 저장되어 있는 데이터의 자료형을 확인하는 함수입니다.

bool 자료형

  • True, False 값을 가질 수 있습니다.
  • Code
a1 = True
a2 = False
print(a1)
print(f"a2 : {a2} - 자료형 : {type(a2)}")
  • Console

int ( 정수 )

  • Code
i1 = 10
i2 = -11
print(i1)
print(f"i2 : {i2} - 자료형 : {type(i2)}")
  • Console

float ( 실수 )

  • Code
f1 = 1.2
print(f1)
print(f"f1 : {f1} - 자료형 : {type(f1)}")
  • Console

str ( 문자열 )

  • Code
s1 = "문자열"
print(f"s1 : {s1} - 자료형 : {type(s1)}")
  • Console

tuple ( 튜플 )

  • Code
tu_1 = ( 1, 2, 3 )
print(f"tu_1 {tu_1}")
print(f"자료형 : {type(tu_1)}")
  • Console

list ( 리스트 )

  • Code
list_1 = [ 'a', 'b', 'c' ]
print(f"list_1 {list_1}")
print(f"자료형 : {type(list_1)}")
  • Console

set ( 세트 )

  • Code
set_1 = { 1, 2, 3 }
print(f"set_1 {set_1}")
print(f"자료형 : {type(set_1)}")
  • Console

dict ( 딕트 )

  • Java의 Map(맵) 형식
  • Code
dict_1 = {"k1":"v1", 'k2':'v2'}
print(f"dict_1 {dict_1}")
print(f"자료형 {type(dict_1)}")
  • Console

자료형 변환

bool() : 불형으로 변환

  • Code
print("- bool() -")
print(bool(0), bool(1), bool(-1))           # False True True
print(bool(0.0), bool(1.2), bool(-2.3))     # False True True
print(bool(''), bool('b'), bool(' '))       # False True True
print(bool([]), bool([1, 2]))               # False True
value1 = 1
cast1 = bool(value1)
print(f"cast1 : {cast1} - type {type(cast1)}")
  • console

str() : 문자열로 변환

  • Code
print("- str() -")
print(str(123), str(-123), str(1.2))
value2 = 123
value2 = str(value2)
print('value2 : ' + value2)
  • Console

int() : 정수형으로 변환

  • Code
print("- int() -")
print(int(True), int(False))
print(int('123'), int('-123'))
print(int(1.2), int(-2.3))
  • Console
  • Error
    print(int('a'))
    • 숫자 형태의 문자열만 int 타입으로 형변환이 가능합니다.

float() : 실수형으로 변환

  • Code
print("- float() -")
print(float(True), float(False))
print(float('123'), float('-123'))
print(float(12), float(-23))
  • Console
  • Error
    print(float('a'))
    • 숫자 형태의 문자열만 float 타입으로 형변환이 가능합니다.

tuple 변환

  • Code
print("- tuple() -")
tu_2 = tuple("abcde")
print(f"tu_2 {tu_2}")
  • Console

list 변환

  • Code
print("- list() -")
list_2 = list("abcde")
print(f"list_2 {list_2}")
  • Console

dict 변환

  • Code
print("- dict() -")
dict_2 = dict([('k1', 'value1'), ('k2', 'value2')])
print(f"dict_2 {dict_2}")
  • Console
  • Error
    # dict_2 = dict("abcde")

0개의 댓글