문자열 인덱싱과 슬라이싱

✒️ 2025-05-19 10:32 내용 수정

Do it! 점프 투 파이썬(2017년 발행) 내용을 정리


1. 문자열 길이 구하기

>>> a = "I'm bullet proof!!"
>>> len(a)
18

python_string 1.png


2. 인덱싱

>>> a = "I'm bullet proof!!"
>>> len(a)
18

>>> a[0]
'I'

>>> a[17]
'!'

>>> a[18]
Traceback (most recent call last):
  File "<python-input-7>", line 1, in <module>
    a[18]
    ~^^^^
IndexError: string index out of range
>>> a = "I'm bullet proof!!"

>>> a[-1]
'!'

>>> a[-5]
'o'

>>> a[-0]
'I'

python_string 2.png


3. 슬라이싱

>>> a = "No we're not gonna stop until we reach it"

>>> b = a[6] + a[-2] + a[19] + a[4] + " " + a[-17] + a[-19]
>>> b
'rise up'
>>> a = "No we're not gonna stop until we reach it"
>>> c = a[19:23]
>>> c
'stop'
>>> a = "No we're not gonna stop until we reach it"
>>> d = a[3:]
>>> d
"we're not gonna stop until we reach it"
>>> a = "No we're not gonna stop until we reach it"
>>> f = a[:23]
>>> f
"No we're not gonna stop"
>>> a = "No we're not gonna stop until we reach it"
>>> g = a[3:-12]
>>> g
"we're not gonna stop until"
>>> a = "Hallo"
>>> a[1] = "e"
Traceback (most recent call last):
  File "<python-input-33>", line 1, in <module>
    a[1] = "e"
    ~^^^
TypeError: 'str' object does not support item assignment

# 문자열을 잘라 새 문자열을 생성
>>> a[:1] + "e" + a[2:]
'Hello'