본문 바로가기

Python

문자열

[ 시퀀스 자료형 ]
- 여러 객체를 저장
- 각 객체들은 순서를 갖는다
- 각 객체들은 첨자를 이용하여 참조가능

* 종류 : 리스트, 튜플, 문자열

* 공통 연산
  인덱싱(indexing) [1]
  슬라이싱(slicing) [1:4]
  연결하기 s + t
  반복하기 s * 4
  멤버쉽 테스트 'a' in s
  길이 정보 len(s)

>>> s = 'abcd' //문자열
>>> L = [100,200,300] //리스트
>>> t = ('tuple', 'object', 1, 2) //튜플

 

[ 여러 줄 문자열 ]
- '''혹은 """로 정의

>>> multiple_lines = '''
first line
second line
third line
'''
>>> print multiple_lines

first line
second line
third line

 

[ 문자열 변경 ]
- 직접적인 변경 불가
- 새로운 이름으로 치환

>>> s = 'snsd is pretty'
>>> s[0] = 'S' //직접적인 변경 불가

Traceback (most recent call last):
  File "<pyshell#59>", line 1, in <module>
    s[0] = 'S'
TypeError: 'str' object does not support item assignment
>>> s = 'S' + s[1:] + '~~!!' //슬라이싱으로 처리
>>> s
'Snsd is pretty~~!!' // SNSD : 소녀시대. ㅋㅋㅋ

 

[ 포매팅 ]
- 문자열을 자유롭게 구성할 수 있음
- 양식과 데이터를 분리

>>> names = ['서현','유리']
>>> for name in names:
 print '%s님 안녕하세요~' %name // names 리스트에 있는 값을 %s에 대체

 
서현님 안녕하세요~
유리님 안녕하세요~

>>> '%s = %s' % ([1,2,3], (1,2,3)) //리스트와 튜플 사용가능 %s로 문자열로 변환
'[1, 2, 3] = (1, 2, 3)'


%d : 10진 정수
%o : 8진수
%x : 16진수 (소문자 영문으로 표시)
%X : 16진수 (대문자 영문으로 표시)

>>> '%3d' % 1 // %d에 3이란 값은 3자리수로 표현
'  1'

>>> '%5.2f' % 1.23456 // 5자리의 수, 소수점은 2자리로 표현(소수점은 반올림)
' 1.23'


/* 사전을 이용한 포멧팅 */
>>> D = {'name':'서현', 'msg':'순수'}
>>> print '%(name)s은 %(msg)s하다' % D
서현은 순수하다


/* 지역 변수의 사전을 넘긴다. 내가 정의한 로컬 변수들이 정의되어 있다. */
>>> vars()
{'a': 1, 'c': 500, 'b': 2, 'name': '\xc0\xaf\xb8\xae', '__builtins__': <module '__builtin__' (built-in)>, 'l': [100, 900, 300], '__package__': None, 'sys': <module 'sys' (built-in)>, 's': 'spam and egg', 'names': ['\xbc\xad\xc7\xf6', '\xc0\xaf\xb8\xae'], 'multiple_lines': '\nfirst line\nsecond line\nthird line\n', '__name__': '__main__', '__doc__': None, 'math': <module 'math' (built-in)>, 'D': {'msg': '\xbc\xf8\xbc\xf6', 'name': '\xbc\xad\xc7\xf6'}}

 

[ 문자열 메쏘드 ]
* 대소문자 변환
- upper() : 대문자변환
- lower() : 소문자변환
- capitalize() : 첫 문자를 대문자로 변환

>>> s = 'spam and ham'
>>> s.upper() // 대문자 변환
'SPAM AND HAM'
>>> s.lower() // 소문자 변환
'spam and ham'
>>> s.capitalize() // 첫 문자를 대문자로 변환
'Spam and ham'


* 검색관련
- count(s) : 문자열 s가 몇 번 발생(사용)했는지 수를 반환
- find(s) : 부분 문자열을 앞(왼쪽)부터 찾음
- rfind(s) : 부분 문자열을 뒤(오른쪽)부터 앞(왼쪽)으로 찾음.
- index(s) : find와 동일하나 찾는 값이 없으면 예외 ValueError 발생

>>> s = 'spam and ham'
>>> s.count('a') // 'a'가 사용된 수를 반환
3
>>> s.find('and') // 'and' 문자열이 어느 위치에 있는지 반환
5
>>> s.find('m')
3
>>> s.rfind('m') // 'm' 문자를 뒤(오른쪽)부터 앞(왼쪽)으로 검색해서 어느 위치에 있는지 반환
11
>>> s.find('m', 4) // 'm' 문자를 4번 위치 이후에 어느 위치에 있는지 반환
11

>>> s.index('egg') // 'egg' 단어가 없기 때문에 예외 발생

Traceback (most recent call last):
  File "<pyshell#111>", line 1, in <module>
    s.index('egg')
ValueError: substring not found

>>> s.index('and') // 'and' 가 어느 위치에 있는지 검색
5

 

* 편집 및 변환
- strip() : 좌우 공백 없앰
- lstrip() : 왼쪽 공백 없앰
- rstrip() : 오른쪽 공백 없앰
- replace(a, b) : a를 b로 바꾼다
- expandtabs() : 탭을 공백 문자로 바꾼다

>>> t = ' spam '
>>> t.lstrip() // 왼쪽 공백 없앰
'spam '
>>> t.rstrip() // 오른쪽 공백 없앰
' spam'
>>> t.strip() // 좌우 공백 없앰
'spam'

'spam and ham'
>>> s.replace('and', 'or') // 'and'를 'or'로 바꾼다.
'spam or ham'
>>>

 >>> t = 'a\tb\tc' // \t : 탭
>>> t
'a\tb\tc'
>>> t2 = t.expandtabs() // 탭을 공백(기본 8자리)으로 변환
>>> t2
'a       b       c'
>>> print t2
a       b       c
>>> t2 = t.expandtabs(4) // 탭의 공백을 4자리의 공백으로 변환
>>> print t2
a   b   c
>>>

 


* 분리와 결합
- split() : 문자열 분리
- join() : 문자열 결합

>>> s
'spam and ham'
>>> s.split() // 단어별로 분리
['spam', 'and', 'ham']

>>> for word in s.split():
 print word, len(word)

spam 4
and 3
ham 3

>>> s.split('and') // split()에 인수값을 주는 경우에 인수를 기준으로 분리
['spam ', ' ham']

>>> mul='''line 1
line 2
line 3'''
>>> mul.split('\n') // 라인단위로 분리
['line 1', 'line 2', 'line 3']
>>> for line in mul.split('\n'):
 print line, len(line)

line 1 6
line 2 6
line 3 6
>>>

>>> t = s.split() // 단어별로 분리
>>> t
['spam', 'and', 'ham']
>>> ' '.join(t) //분리한 단어를 공백으로 합침
'spam and ham'
>>> ''.join(t)
'spamandham'
>>> '\n'.join(t) //분리한 단어를 줄을 바꿔서 합침
'spam\nand\nham'
>>> print '\n'.join(t) //분리한 단어를 줄을 바꿔서 합침
spam
and
ham
>>>

 

* 정렬(alignment)
- center()
- ljust()
- rjust()


>>> s
'spam and ham'
>>> s.center(60) // 60자 사이에 가운데로 정렬
'                        spam and ham                        '
>>> s.ljust(60) // 60자 사이에 왼쪽으로 정렬
'spam and ham                                                '
>>> s.rjust(60) // 60자 사이에 오른쪽으로 정렬
'                                                spam and ham'
>>>

 


* 문자열 질의
- isalnum() : 영문자 숫자인지 여부
- isalpha() : 영문자인지 여부
- isdigit() : 숫자인지 여부
- islower() : 소문자인지 여부
- isspace() : 공백문자인지 여부
- istitle() : 제목인지 여부 (단어 첫부분이 대문자일 경우 제목으로 인식)
- isupper() : 대문자인지 여부


>>> 'Gone with the wind'.istitle() // 제목인지 여부
False
>>> 'Gone With The Wind'.istitle() // 제목인지 여부(단어 첫부분이 대문자일 경우 제목으로 인식)
True

>>> 'abcd1234'.isalnum() // 영문자 숫자인지 여부
True
>>> '1234'.isdigit() // 숫자인지 여부
True

 


* string 모듈
- digits, octdigits, hexdigits, letter, lowercase, uppercase, punctuation, printable, whitespace

>>> import string
>>> string.digits
'0123456789'
>>> string.octdigits
'01234567'
>>> string.letters
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
>>> string.uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>>

/* 숫자인지의 여부를 출력 */
>>> s = '123'
>>> for ch in s:
 if ch in string.digits:
  print '%s is in digits' % ch

  
1 is in digits
2 is in digits
3 is in digits


>>> s = 'spam'
>>> string.upper(s)
'SPAM'
>>> s.upper() // 1.6버전 이후로 이 방법을 추천
'SPAM'

 

* 모듈 함수
- 대부분 문자열 메쏘드와 동일
- capwords(s) : 각 단어의 첫 문자를 대문자로 변환
- zfill(s, n) : 왼쪽의 빈자리를 0으로 채운다

>>> string.capwords('spam and ham') // 각 단어의 첫 문자를 대문자로 변환
'Spam And Ham'
>>> string.zfill('123', 6) // 6자리를 확보하여 왼쪽의 빈자리를 0으로 채운다
'000123'
>>>

 

[ 유니코드 ]
- 다국어 문자를 표현하기 위해 사용
- 1.6부터 지원
- 한글 표현이 안될 경우 한글 코덱을 설치

>>> unicode('한글')
u'\ud55c\uae00'

>>> unicode('한글').encode('euc-kr')
'\xc7\xd1\xb1\xdb'

>>> unicode('한글').encode('utf-8')
'\xed\x95\x9c\xea\xb8\x80'

 

[ 문서 문자열 ]
* 모듈이나 함수, 메쏘드를 해설하는 문서 문자열

* 문서 문자열의 참조
- __doc__ 속성
- 좀 더 자세한 설명을 보려면 help를 이용
  형식화해서 표시
  하위 함수나 클래스의 문서 문자열도 표시


>>> import string
>>> string.upper
<function upper at 0x0266D070>
>>> print string.upper.__doc__
upper(s) -> string

    Return a copy of the string s converted to uppercase.

   
>>>
>>> help(string.upper)
Help on function upper in module string:

upper(s)
    upper(s) -> string
   
    Return a copy of the string s converted to uppercase.


* 문서 문자열 만들기
- 모듈 : 파일의 첫 문자열
- 함수 - 함수의 첫 문자열
- 클래스, 메쏘드 등도 마찬가지

 

'Python' 카테고리의 다른 글

맥(Mac)에서 파이썬(Python) 설치하기  (5) 2015.06.18
수치 자료형과 연산자  (0) 2009.08.23
제어문  (0) 2009.08.23
Python 기초  (0) 2009.08.23