아카이브/Python

[Python 자료형] 문자열 (String) - 2

될성부른떡잎 2015. 7. 14. 17:39


[Python 자료형] 문자열 (String) - 2


문자열 함수


- 문자열 포맷팅 : format 함수를 이용하면 서식문자와 같이 대입이 가능하다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#-*- coding: utf-8 -*-
 
# 숫자 대입
print "number : {0}".format(10)
 
# 숫자 변수 대입
num = 10
print "number : {0}".format(num)
 
# 두개의 값 대입
print "number : {0}, string : {1}".format(100'test')
 
# 이름으로 대입
print "number : {num}, string : {str}".format(num=100str='test')
cs

1
2
3
4
number : 10
number : 10
number : 100, string : test
number : 100, string : test
cs


- 대소문자 변환 : upper(), lower()

1
2
3
4
5
6
7
8
#-*- coding: utf-8 -*-
 
str = 'AbCdEf'
 
# str의 모든 문자를 대문자로 변환 
print str.upper()
# str의 모든 문자를 소문자로 변환
print str.lower()
cs

1
2
ABCDEF
abcdef
cs


- 문자 위치 반환 : find(), index()

1
2
3
4
5
6
7
8
9
10
11
12
#-*- coding: utf-8 -*-
 
str = 'hello world!'
 
# str의 문자 중 'w'의 위치 반환
print str.find('w')
print str.index('w')
 
# find는 존재하지 않는 문자 검색시 -1 반환
print str.find('x')
# index는 존재하지 않는 문자 검색시 에러 발생!!
print str.index('x')
cs

1
2
3
4
5
6
7
Traceback (most recent call last):
  File "C:/Users/Admin/PycharmProjects/Day/test.py", line 12in <module>
    print str.index('x')
ValueError: substring not found
6
6
-1
cs


- 문자 수 세기, 삽입 : count(), join()

1
2
3
4
5
6
7
8
#-*- coding: utf-8 -*-
 
str = 'hello world!'
pick = ',,'
 
# str의 해당 문자 수 반환
print str.count('l')
print pick.join(str)
cs

1
2
3
h,,e,,l,,l,,o,, ,,w,,o,,r,,l,,d,,!
cs

- 공백 삭제 : lstrip(), rstrip(), strip()

1
2
3
4
5
6
7
8
#-*- coding: utf-8 -*-
 
str = '\t hello world! \t'
 
# str의 해당 문자 수 반환
print str.lstrip()
print str.rstrip()
print str.strip()
cs

1
2
3
hello world!     
     hello world!
hello world!
cs


- 문자열 치환, 나누기 : replace(), split()

1
2
3
4
5
6
7
8
9
10
11
#-*- coding: utf-8 -*-
 
str = 'hello world!'
# str의 world를 james로 치환
print str.replace('world''james')
 
str2 = 'Data Structure Using Python'
# str2를 공백을 기준으로 나누기
print str2.split()
# str2를 알파벳 't'를 기준으로 나누기
print str2.split('t')
cs

1
2
3
hello james!
['Data''Structure''Using''Python']
['Da''a S''ruc''ure Using Py''hon']
cs


정리

위 함수들은 위키독스의 점프 투 파이썬 사이트를 참조하였으며 더 많은 내용들은 파이썬 도큐먼트를 참고하길 바란다.

(점프 투 파이썬 : https://wikidocs.net/1)

(파이썬 도큐먼트 : https://docs.python.org/3/contents.html)