본문 바로가기

Python

[Python3] 기본 문법 정리

반응형

문자열 Index

s = 'Sukho'
print ('length of s', len(s))
print (s[0])
print (s[1])
print (s[2])
print (s[3])
print (s[4])

 

문자열 Index (뒤에서부터)

s = 'Sukho'
print (s[-1])
print (s[-2])
print (s[-3])
print (s[-4])
print (s[-5])

 

문자열 썰기 (slicing)

s = 'Sukho'
print (s)
print (s[0:4])
print (s[:4])  # 시작 인덱스를 생략
print (s[5:9])
print (s[5:])  # 끝 인덱스를 생략
print (s[:4] + s[5:])
print (s[2:-2]) # s[시작위치 : 안나오게 할 위치]

 

문자열 - for loop

  • 각 문자에 대하여 어떤 작업을 할 수 있음
  • Unix 쉘 스크립트의 for each 문과 비슷
for char in 'SALE':
    print('<' + char + '>')

 

리스트(list)

  • 목록 형태의 자료를 저장

  • 대괄호를 사용

    pets = ['cat', 'dog', 'parrot', 'turtle']
    print(pets[0:2])    # 슬라이싱
    print(pets[-3:])    # 슬라이싱
  • for 루프 사용 가능

    for p in pets:
        print(p)
  • 결과값

 

List - Mutable

  • List는 Mutable object

  • 원소의 값을 변경할 수 있고, 순서를 바꿀 수 있음

    L = ['a', 'b', 'c']
    L[0] = 'A'
    print(L)
    
    L[0], L[1] = L[1], L[0]
    print(L)
    
    del L[1]
    print(L)

 

리스트의 중첩, 붙이기

numbers = [1, 2, 3, 4]
print(numbers)

CJK = ['Chinese', 'Japanese', 'Korean']
print(CJK)

print([numbers, CJK])
print([numbers, CJK][1][1])

for x in numbers + CJK:
    print(x)

 

Tuple

  • 소괄호 사용, 생략 가능

  • 값을 바꿀 수 없음 (=immutable)

  • 값이 바뀌지 않아야할 곳에 사용하면 안심

    # 소괄호 사용, 생략 가능
    parents = ('mother', 'father')
    siblings = 'brother', 'sister'
    print(siblings)
    
    # immutable이기 때문에 에러
    del parents[0]

 

Dictionary

  • 둘 씩 짝지어진 데이터

    URLS = dict()
    URLs['goo.gl/8asd0'] = 'hochoon-dev.tistory.com'
    URLs['goo.gl/nRv1Yv'] = 'www.mapo.go.kr'
    URLs['goo.gl/37aRj4'] = 'www.infinitybooks.co.kr'
    print(URLs)
    print(len(URLs))
    print(URLs.keys())
    print(URLs.values())

 

 


반응형

'Python' 카테고리의 다른 글

[Python3] 제어문 관련 정리  (0) 2020.03.12
[Python3] Dictionary 관련 정리  (0) 2020.03.11
[Python3] List 관련 정리  (0) 2020.03.11
[Python3] 문자열 관련 정리  (0) 2020.03.10
[Python3] 기본 문법 정리2  (0) 2020.03.09