12. Python

[파이썬 기본편_14] 문자열 슬라이싱 a[ : : ]

도피디 2023. 8. 24. 21:52
반응형

슬라이싱: 범위를 정한 부분을 가져옴

 

 

 

a = "Life is too short, You need Python"
print(a[0:4])

 

a[0:4] --> a의 0번째부터~4미만까지 가져와~~~~

 

출력값: Life

 

 

 


 


 

  1.  
a = "Life is too short, You need Python"
b = a[19:]
print(b)

 

a[19: ] : a의 19번째부터 끝까지

출력값: You need Python

 

 

 

 

 

 

    2. 

 

a = "Life is too short, You need Python"
b = a[:]
print(b)

 

a[  :  ] --> a의 처음부터 끝까지

출력값: Life is too short, You need Python

 

 

 

 

 

 

    3. 

 

a = "Life is too short, You need Python"
b = a[::2]
print(b)

 

a[ :  : 2]  -->  a의 처음부터 끝까지 2칸 간격으로

출력값: Lf stosot o edPto

 

 

 

 

 

   4.

 

a = "Life is too short, You need Python"
b = a[::-1]
print(b)

 

a[ :  : -1]  -->  a의 처음부터 끝까지, 근데 거꾸로 셈!

출력값: nohtyP deen uoY ,trohs oot si efiL

 

 

 

 

 

 

 

 

 


 

 

실무에서 쓰일 수 있는 케이스

 

 

a = "20230331Rainy"
date = a[:8]
weather = a[8:]
print(date)
print(weather)

 

문자열을 갈라야 할 때

 

a[ : 8] --> 처음부터 8번미만 인덱스까지

a[8 : ] --> 8번 인덱스부터 끝까지

 

출력값: 

20230331
Rainy

 

 

 

 

 

 

 

반응형