[Python] 문자슬라이싱

Posted by nkjok
2025. 7. 21. 08:39 낙서장[1]/94. Python
반응형

print("Mint Chocolate")
print("Mint Chocolate"[0:4])
print("Mint Chocolate"[:4])
print("Mint Chocolate"[5:14])
print("Mint Chocolate"[5:])
print("Mint Chocolate"[:])
# 결과
Mint Chocolate
Mint
Mint
Chocolate
Chocolate
Mint Chocolate


➕ 슬라이싱 간격 설정
문자열[start:end:step]
슬라이싱 구문에 step을 추가해 특정 간격으로 문자를 선택할 수 있습니다.
step을 2로 지정하면 문자를 2개마다 하나씩 선택합니다.
# 0부터 13까지 2의 간격으로 선택
print("Mint Chocolate"[0:14:2])

# 처음부터 끝까지 5의 간격으로 선택
print("Mint Chocolate"[::5])
# 결과
Mn hclt
MCl


step을 0으로 지정하면 ValueError가 발생합니다.
print("Mint Chocolate"[::0])
# 결과
ValueError: slice step cannot be zero

반응형

'낙서장[1] > 94. Python' 카테고리의 다른 글

[Python] 리스트 LIST  (2) 2025.07.23
[Python] 비교연산자  (1) 2025.07.22
[Python] 숫자 연산  (3) 2025.07.21
[Python] 패킷 필터 도구 코드 해설  (0) 2025.05.27
[Python] 함수 def 사용방법  (0) 2025.02.09