반응형
일반 코드
colors = ["a", "b", "c", "d", "e"]
result = ""
for s in colors:
result += s
print(result)
파이써닉 코드
# pythonic code
colors = ["red", "blue", "green", "yellow"]
result = "".join(colors)
print(result)
for loop로 append하는 것보다 join으로 한번에 처리하는 것이 더 효율적이다. 그리고 다른 사람들이 이러한 코드를 짜 놓았을 때 이해할 수 있어야 하기 때문에 pythonic code를 알고 가는 것이 중요하다.
Split 함수
빈칸을 기준으로 문자열 나누기
items = 'zero one two three'.split()
print(items)
","을 기준으로 문자열 나누기
example = 'python,jquery,javascript'
print(example.split(","))
리스트의 각 값을 a,b,c, 변수로 Unpacking
example = 'python,jquery,javascript'
a, b, c = example.split(",")
"."을 기준으로 문자열을 나누고 Unpacking
example = 'cs50.gachon.edu'
subdomain, domain, tld = example.split(".")
Join 함수
: String List를 합쳐 하나의 String으로 바꿀 때에 사용한다.
colors = ['red', 'blue', 'yellow', 'green']
result = "".join(colors)
print(result)
result = ' '.join(colors)
print(result)
result = ', '.join(colors)
print(result)
result = '-'.join(colors)
print(result)
redblueyellowgreen
red blue yellow green
red, blue, yellow, green
red-blue-yellow-green
반응형
'AI > python' 카테고리의 다른 글
파이썬 기초 6) 리스트 (0) | 2021.01.09 |
---|---|
파이썬 기초 5) 예외 처리, bool값과 논리 연산 (0) | 2021.01.09 |
파이썬 기초 4) 튜플, while문 (0) | 2021.01.08 |
파이썬 기초 3) 딕셔너리 (0) | 2021.01.08 |
파이썬 기초 2) 리스트, for문, 모듈 (0) | 2021.01.08 |