Programming/Python

[Python] 문자열(String) - (1) 문자열 인덱스/문자열 조작함수

Yejii 2020. 5. 18. 20:55

문자열이란? 

여러개의 char가 결합된 형태를 말한다.

자바와 달리 문자(char)와 문자열(string)을 구분하지 않는다.

 

1) 문자열 인덱스

특징

  • 문자열은 문자의 배열과 동일하다.

  • 즉, 배열의 인덱스로 요소 추출 가능 (정방향 인덱스, 역방향 인덱스 존재)

  • 범위를 지정하여 문자열의 일부 요소를 추출할 수도 있다.

예제 설명

    • 인덱스를 사용하여, 문자열 요소에 접근

    • 범위를 지정하여, 문자열의 일부 요소들에 접근

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#1번 문자열 인덱싱(요소접근 방법)
#예제1
str = 'Hello Python'
print('str:',str)
 
#문자'e'출력
print('str[1]:'str[1]) #정방향 인덱스 사용
print('str[-11]:'str[-11]) #역방향 인덱스 사용
 
#문자'P'출력
print('str[6]:'str[6]) #정방향 인덱스 사용
print('str[-6]:'str[-6]) #역방향 인덱스 사용
 
#예제2
str = 'Hello Python'
print('str:',str)
 
#'Hello'만 범위로 지정
print('str[0:5]:',str[0:5])
print('str[-12:-7]:',str[-12:-7])
print('str[:5]:',str[:5]) #시작 위치 생략 가능
 
#'Python'만 범위로 지정
print('str[6:12]:',str[6:12])
print('str[-6:-12]:',str[-6:-12])
print('str[6:]:',str[6:]) #끝 위치 생략 가능
cs

 

2) 문자열 조작함수 - replace(), split(), splitline(), join()

1. replace(old, new[,cnt]) : 문자열의 old부분을 new로 교체

특징

  • cnt는 교체 횟수

  • cnt를 지정하지 않으면 모든 old값이 new로 교체된다

예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#문자열 조작 함수
#1. replace(old, new[,cnt]) 예제
 
s1 = 'abcdefg'
 
print(s1.replace('bc','123')) #원본 문자열에서 bc부분을 123으로 교체
#결과: a123defg
 
print(s1) #실행 후에도 원본 문자열은 바뀌지 않는다.
#결과: abcdefg
 
s2='one str two str three str'
 
print(s2.replace('str','box',2))#원본 문자열에서 'str' 2개만 'box'로 변경
#결과:one box two box three str
 
print(s2.replace('str','box'))#원본 문자열에서 'str' 모두를 'box'로 변경
#결과:one box two box three box
 
print(s2)#실행 후에도 원본 문자열은 불변
#결과: one str two str three str
 
cs
 

2. split([delim[,max]) :  문자열을 delim(구분자)를 기준으로 분할하여, 문자열 리스트를 반환

특징

  • delim을 생략하면 스페이스가 default값으로 사용된다.

  • max는 분할 개수를 뜻한다.

예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#문자열 조작 함수
#2.split([delim[,max]) 예제
 
s2='one two three four five' 
 
print(s2.split())#구분자를 지정하지 않으면 공백이 기본 구분자가 된다
#결과:['one', 'two', 'three', 'four', 'five']
 
s2='one,two,three,four,five'
 
print(s2.split(','))#구분자를 ','로 지정
#결과:['one', 'two', 'three', 'four', 'five']
 
print(s2.split(',',2))#구분자 분할 개수를 2개로 지정
#결과:['one', 'two', 'three,four,five']
cs
 

3. splitline(num):  문자열을 '\n'기준으로 분할. '\n'을 제거한 리스트를 반환

특징

  • num이 양수면, '\n' 제거 안함

예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#문자열 조작 함수
#3. splitline(num) 예제
 
s1='one line\ntwo line\nthree line'
 
print(s1.splitlines())#\n을 구분자로 문자열 분할. 분할된 문자열의 \n은 제거해서 반환
#결과:['one line', 'two line', 'three line']
 
print(s1.splitlines(3))#파라메터 값이 양수면 '\n'제거 하지 않고 반환한다.
#결과:['one line\n', 'two line\n', 'three line']
 
s2='one line\n\ntwo line\n\nthree line'
 
print(s2.splitlines())
#결과:['one line', '', 'two line', '', 'three line']
 
print(s2.splitlines(1))#파라메터 값이 양수일 경우, 숫자 크기와 상관없이 결과는 동일
#결과:['one line\n', '\n', 'two line\n', '\n', 'three line']
print(s2.splitlines(2))
#결과:['one line\n', '\n', 'two line\n', '\n', 'three line']
cs

 

4. join(str):  문자열들을 하나의 문자열로 결합. 각 문자열 사이 구분자 추가 가능

예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#문자열 조작 함수
#4.join(str) 예제
 
delim = '/' #구분자
 
s1=('aaa','bbb','ccc'#문자열 튜플: 불변
s2=['aaa','bbb','ccc'#문자열 리스트: 가변
 
#튜플의 요소를 모두 연결하여 하나의 문자열 반환. delim을 구분자로 사용
print(delim.join(s1)) 
#결과:aaa/bbb/ccc
 
#리스트의 요소를 모두 연결하여 하나의 문자열 반환. delim을 구분자로 사용
print(delim.join(s2)) 
#결과:aaa/bbb/ccc
cs