python의 문자열은 immutable
하기 때문에 단순히 인덱스로 변환하려 하면 에러가 발생한다.
s = 'toeic'
s[1] = 'p'
>>> TypeError: 'str' object does not support item assignment
문자열의 일부를 수정하고 싶다면?
방법 1. 새로운 문자열을 만든다.
s = 'toeic'
s = s[:1] + 'p' + s[2:]
print(s)
>>> tpeic
방법 2. list
로 변환해 수정한 후, join()
함수를 사용해 문자열로 변환한다.
s = 'toeic'
arr = list(s)
print(arr)
>>> ['t', 'o', 'e', 'i', 'c']
arr[1] = 'p'
s = ''.join(arr)
print(s)
>>> 'tpeic'