본문 바로가기
Python/Python

문자열 뒤집기 - 문자열 슬라이싱

by Sondho 2020. 5. 8.

문자열 슬라이싱(Slincing)?

  • char[start:end:step] 
  • start와 end의 생략이 가능하다.
  • start를 생략하면 맨 처음이라는 뜻이다.
  • end를 생략하면 맨 끝이라는 뜻이다.
  • step은 1일 때 생략이 가능
  • range(start, end, step)과 비슷

start의 생략

char = 'Life is too short, You need Python'
print(char[:4]) # print(char[0:4])로 쓸 수도 있다.


# 실행결과
Life

line 2의 char[:4]는 char에서 맨 처음부터 3까지의 문자열을 추출하라는 뜻이다.

char[0] = L

char[1] = i

char[2] = f

char[3] = e

char[0:4] = Life

 

end의 생략

char = 'Life is too short, You need Python'
print(char[4:]) # char[4]부터 맨 끝 까지


# 실행결과
 is too short, You need Python

 

 

 

 

step이 2이상일 때

char = 'Life is too short, You need Python'
print(char[0:4:2]) # char[0]부터 char[3]까지 2씩 건너뛰어서 추출


# 실행결과
Lf

1line 2의 char[0:4:2]는 char에서 0부터 3까지 2씩 증가시켜서 추출하라는 뜻이다.

char[0] = L

char[2] = f

char[0:4:2] = Lf

 

 

반대로도 가능하다.

char = 'Life is too short, You need Python'
print(char[4:0:-1]) 


# 실행결과
 efi

char[4] = 공백

char[3] = i

char[2] = f

char[1] = e

char[4:0:-1] =  ife

line 2의 경우에는 4부터 1까지여서 맨 처음 숫자 추출이 되지 않는다.

맨 처음 숫자를 추출하고 싶다면 end를 생략하면 된다.

char = 'Life is too short, You need Python'
print(char[4::-1])


# 실행결과
 efiL

 

맨 마지막을 -1로 쓸 수도 있다.

char = 'Life is too short, You need Python'
print(char[0])
print(char[1])
print(char[2])
print()
print(char[-1])
print(char[-2])
print(char[-3])


# 실행결과
L
i
f

n
o
h

 

문자열 뒤집기

위의 내용을 이해했다면 쉽게 생각할 수 있다.

char[:]을 하면 전부 출력할 수 있고 char[::1]로 바꿔 쓸 수 있다.

char = 'Life is too short, You need Python'
print(char[:]) # char[::1]로 쓸 수도 있다.


# 실행결과
Life is too short, You need Python

 

반대로 출력하고 싶다면

char[::-1]로 쓰면 된다. 전부 추출하되 -1로 즉, 반대로 추출한다는 뜻이 된다.

char = 'Life is too short, You need Python'
print(char[::-1])


# 실행결과
nohtyP deen uoY ,trohs oot si efiL

댓글