반응형

 

 

 

일반 코드

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

 

 

 

 

반응형

+ Recent posts