Python/Basics

[파이썬 기초 문법] - 내용 정리 1(Print, 변수, 문자열, 리스트, 튜플, 딕셔너리)

ro-jun 2024. 10. 17. 11:44
728x90
반응형

Print

  • print 함수의 sep인자를 사용하면, 한 칸의 공백대신 입력문자가 출력된다.
print("first", "second")
print("first", "second","third", sep="---")

 

first second
first second first---second---third
  • 줄바꿈 없이 출력하기.
print("first");print("second")
print("first", "second", end=""); print("third")

 

first
second
first secondthird

문자열

  • 문자열은 immutable(불변)
lang = 'python'
lang[0] = 'P'
print(lang)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-13-ba8eb7824ab8> in <cell line: 2>() 1 lang = 'python' ----> 2 lang[0] = 'P' 3 print(lang)
TypeError: 'str' object does not support item assignment
  • replace 메서드 변경 안되는 경우
string = 'abc'
string.replace('a', 'A')
print(string)

 

abc

  • 문자열 첫 글자 대문자 + 소문자 변환 (capitalize) 메서드
me = "I am A Boy."
print(me)
me = me.capitalize()
print(me)

 

I am A Boy.
I am a boy.

 

  • startswith, endswith 메서드 사용법
file_name = "보고서.xlsx"
file_2024 = "2024_보고서.xlsx"
print(file_2024.startswith("2024"))
print(file_name.endswith((".xlsx", ".xls")))

 

True
True

List

  • join 메서드 - 리스트 값을 .join()앞의 문자와 함께 문자열로 합치기
enter_list = ["엔비디아", "AMD", "삼성전자", "LG전자", "테슬라"]
print(enter_list)
print("/".join(enter_list))

 

['엔비디아', 'AMD', '삼성전자', 'LG전자', '테슬라']
엔비디아/AMD/삼성전자/LG전자/테슬라

Tuple

  • 튜플 정의하기
my_tuple = ("밀가루", "쌀", "보리")
print(my_tuple)
print(type(my_tuple))
other_tuple = "밀가루", "쌀", "보리"
print(other_tuple)
print(type(other_tuple))
my_tuple2 = (1)
print(my_tuple2)
print(type(my_tuple2))
my_tuple3 = (1, 2, 3)
print(my_tuple3)
print(type(my_tuple3))
my_tuple3[0] = 2
('밀가루', '쌀', '보리')
<class 'tuple'>
('밀가루', '쌀', '보리')
<class 'tuple'>
1
<class 'int'>
(1, 2, 3)
<class 'tuple'>
---------------------------------------------------------------------------
TypeError Traceback (most recent call last) <ipython-input-10-db57430e2ae4> in <cell line: 10>() 8 print(my_tuple3) 9 print(type(my_tuple3)) ---> 10 my_tuple3[0] = 2 TypeError: 'tuple' object does not support item assignment
  • 튜플 언팩킹
my_tuple = ('밀가루', '쌀', '보리')
a, b, c = my_tuple
print(a, b, c)
print(my_tuple)
밀가루 쌀 보리
("밀가루", "쌀", "보리")

Dictionary

  • 별 표현식을 통한 데이터 언패킹
# score 정렬 후 중심 기준 6개 start expression 바인딩하기.
scores = [8.8, 8.9, 8.7, 9.2, 9.3, 9.7, 9.9, 9.5, 7.8, 9.4]
a, b, *score, c, d = scores
print(a)
print(b)
print(score)
print(c)
print(d)
8.8
8.9
[8.7, 9.2, 9.3, 9.7, 9.9, 9.5]
7.8
9.4
  • 딕셔너리 생성, 추가, 인덱싱
it_items = {"핸드폰": [130, 300],
           "노트북": [200, 10]}
print(it_items)
it_item["컴퓨터"] = [300, 10]
print(it_items)
print("현재 " + str(it_item["핸드폰"][0]) + "만원의 핸드폰이 " + str(it_item["핸드폰"][1]) + " 대 존재합니다.")
print(f'현재 {it_item["컴퓨터"][0]}만원의 컴퓨터가 {it_item["컴퓨터"][1]} 대 존재합니다.')

 

{'핸드폰': [130, 300], '노트북': [200, 10]}
{'핸드폰': [130, 300], '노트북': [200, 10], '컴퓨터': [300, 10]}
현재 130만원의 핸드폰이 300 대 존재합니다.
현재 300만원의 컴퓨터가 10 대 존재합니다.

 

  • tuple, list를 zip을 활용하여 dictionary 변환하기
keys = ("컴퓨터", "노트북", "핸드폰")
values = (300, 200, 130)
it_items = dict(zip(keys, values))
print(it_items)
weekend = ["월요일", "화요일", "수요일", "목요일", "금요일", "토요일", "일요일"]
dates = ["2024_10_14", "2024_10_15", "2024_10_16", "2024_10_17", "2024_10_18", "2024_10_19", "2024_10_20"]
days = dict(zip(weekend, dates))
print(days)

 

{'컴퓨터': 300, '노트북': 200, '핸드폰': 130}
{'월요일': '2024_10_14', '화요일': '2024_10_15', '수요일': '2024_10_16', '목요일': '2024_10_17', '금요일': '2024_10_18', '토요일': '2024_10_19', '일요일': '2024_10_20'}

https://wikidocs.net/book/922

728x90
반응형