아카이브/Python

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

될성부른떡잎 2015. 7. 14. 14:03


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


문자열 생성 방법

문자열은 " 또는 '를 이용해서 만들 수 있다. " " 안에는 ' 가 들어갈 수 있고, ' ' 안에는 " 가 들어갈 수 있다. 아래 코드로 확인해 보자.

1
2
3
4
5
6
7
#-*- coding: utf-8 -*-
 
str1 = "I'm yours"
str2 = 'He said, "Python is fun!!"'
 
print str1
print str2
cs

1
2
I'm yours
He said, "Python is fun!!"
cs

""" """ 또는 ''' '''을 이용해서 여러 줄의 문자열도 간단히 표현 가능하다.
1
2
3
4
5
6
#-*- coding: utf-8 -*-
str = """
Life is too short,
You need python
"""
print str
cs

1
2
Life is too short,
You need python
cs

이스케이프 코드도 사용 가능하다.
1
2
3
str = "\tLife is too short,\n \tYou need python"
 
print str

cs

1
2
    Life is too short,
     You need python
cs


아래 5개의 이스케이프 코드를 많이 사용한다. 나머지는 필요할 때마다 찾아서 사용하면 된다.

 코드

기능 

\n

줄바꿈 

\t 

수평탭

\\

문자 역슬래쉬 

\' 

작은 따옴표 

\"

큰 따옴표 








문자열 연산

- 문자열 합치기 (str1 + str2)

1
2
3
4
5
6
#-*- coding: utf-8 -*-
 
str1 = "python is "
str2 = "good"
 
print str1 + str2
cs

1
python is good
cs

- 문자열 반복 (str * n)
1
2
3
#-*- coding: utf-8 -*-
 
print '='*50
cs

1
==================================================
cs


인덱싱과 슬라이싱

인덱싱은 해당 번호의 순서에 있는 데이터를 가져오는 것이고, 슬라이싱은 해당 범위 내의 데이터를 모두 가져오는 것이다.

1
2
3
4
5
6
7
8
#-*- coding: utf-8 -*-
 
str = "Life is too short, You need Python."
 
print str[12]    # 인덱스는 0부터 시작, 13번째 글자 출력
print str[0:12]  # 인덱스 0부터 11까지 출력, 12는 출력 X
print str[:12]   # 처음부터 인덱스 11까지 출력
print str[12:]   # 인덱스 12부터 끝까지 출력
cs

1
2
3
4
s
Life is too 
Life is too 
short, You need Python.
cs


서식문자의 사용

파이썬은 문자열 포맷팅을 지원한다.

 코드

설명 

%d

정수(10진수) 

%

실수(부동소수점) 

%

문자 

%

문자열 

%

8진수 

%

16진수 

%% 

문자 %









- 숫자, 문자 대입

1
2
3
4
5
6
7
8
9
#-*- coding: utf-8 -*-
 
num1 = 3
num2 = 5
str = "Python"
 
print "num1 : %d" % num1
print "num1 : %d, num2 : %d" % (num1, num2)
print "%s is my favorite computer language." % str
cs

1
2
3
num1 : 3
num1 : 3, num2 : 5
Python is my favorite computer language.
cs


- 정렬, 공백, 소수점 표현

서식문자 앞에 부호, 숫자에 따라 데이터의 표현이 달라진다.

- : 왼쪽 정렬, 정수 : 자리수, 소수점 : 소수점 자리수

1
2
3
4
5
6
7
#-*- coding: utf-8 -*-
 
num1 = 3
num2 = 5.2381726
 
print "num1 : %10d" % num1
print "num2 : %-10.4f" % num2
cs

1
2
num1 :          3
num2 : 5.2382
cs


문자열 내장 함수에 대한 설명이 남았는데 다음 포스팅에서 이어가도록 하겠다.