59doit

[Python] 인덱싱, 연산, 슬라이싱 본문

Programming/Python(파이썬)

[Python] 인덱싱, 연산, 슬라이싱

yul_S2 2022. 10. 23. 12:14
반응형

 

인덱싱 ; 문자열 자리

[ ](대괄호) 이용

ex) -1 : 뒤에서 첫번째, 0 : 앞에서 첫번째 

a = "life is too short, you need python"
b = a[-1]
print(b)
#n

a = "life is too short, you need python"
c = a[0]
print(c)
#L

a[-1] > 문자열을 뒤에서부터 읽는다(-)
a[0] > 문자열 맨앞자리는 1이 아닌 0부터 시작한다.

 

 

 

문자열 길이 len( ) / 문자열 곱하기 *x

#문자열 길이
d = len(a)
print(d) 
#34


# 문자열 곱하기
e = "python"
f = e*2
print(f)
#pythonpython

 

문자열 더해서 연산하기  :  +

# 문자열 더해서 연산하기
head = "안녕"
tail = "하세요"
head + tail
# '안녕하세요'

 

 

문자열 슬라이싱 ; a[0:x] 첫번째자리에서부터 x번째까지 즉, ★ a[ 시작번호, 끝번호 ]

기초

a = "life is too short, you need python"
a[0:4]
# <출력> life
a[0:5]
# <출력> life ; 띄어쓰기포함
a[5:7]
# <출력> is
a[12:17]
# <출력> short
a[19:]
# <출력> you need python
a[:17]
# <출력> life is too short
a[:]
# <출력> life is too short, you need python
a[19:-7]
# <출력>  you need

a[:] : 처음부터 끝까지 ; 콜론사이에 띄어쓰기는 없음 
a[19:-7] : 20번째부터 뒤에서 7번째까지 

 

 

 

 

슬라이싱으로 문자열 나누기

a="20220826sunny"

date=a[:8]
print(date)
# <출력> 20220826

weather=a[8:]
print(weather)
# <출력> sunny

 

 

 

특정문자 하나를 바꾸려면 ?

 pithon > python

# pithon > python
word="pithon"

b = word[:1] #p
print(b)
c = word[2:] #thon
print(b+'y'+c)
# <출력> python

 

replace (old,new)

- old : 현재 문자열에서 변경하고 싶은 문자
- new: 새로 바꿀 문자

bytearray인 문자열을 변경할 수 있는 메서드이다. 즉, 문자열에서만 사용 가능한 함수인 것이다.

그 밖에 리스트, 튜플에 replace를 시도해 보면 AttributeError 에러가 발생한다.

word="pithon"
print(word.replace("i","y")) 
# <출력> python

 

반응형

'Programming > Python(파이썬)' 카테고리의 다른 글

[Python] 리스트  (0) 2022.10.27
[Python] 문자열 관련함수  (0) 2022.10.26
[Python] 포맷팅 format  (0) 2022.10.25
[Python] 인덱싱 index(),find()  (0) 2022.10.24
[Python] 줄 바꿈 , \b (삭제)  (0) 2022.10.22
Comments