Computers/Language python

파이썬 문자열 substring / slicing

emzei 2012. 3. 14. 16:14

substring


>>> s = "anything"


  | a | n | y  | t  | h |   i  |  n | g |

 0    1   2    3    4    5    6    7   8

-8  -7  -6  -5   -4   -3   -2   -1 


이렇게 보면 이해가 좀 더 될듯   



>>> print s

anything

>>> print s[:]

anything

>>> print s[0:]

anything

>>> print s[:-1]

anythin

>>> print s+s[0:-1+1]

anything

>>> print s[-1]

g

>>> print s[0:-1]

anythin

>>> print s[:3]+s[3:]

anything




----------------------------------------------------------------------------------------------------

slicing

 <string>[ start : stop : step ]

각각 생략될 경우 기본 값은 start = 0, stop = size of string, step = 1

ex>

>>> s = 'hello'

>>> s[::-1]

'olleh'

>>> s[::2]

'hlo'



  문자열 연결, 반복 가능

>>> s = 'omg'

>>> t = ' means oh my god'


연결 ex)

>>> s + t

'omg means oh my god'


반복 ex)

>>> s*3

'omgomgomg'


▷ 문자열의 (원소?)값은 변경되지 않음

>>> s[0]=i


Traceback (most recent call last):

  File "<pyshell#27>", line 1, in <module>

    s[0]=i

TypeError: 'str' object does not support item assignment


▷ 변경을 원하면 슬라이싱과 연결 연산을 이용한다

 ex)

>>> s = 'i'+s[1:]

>>> s

'img'


▷ 문자열 길이는 len(<string>) 이용

▷ 멤버십 테스트를 통해 문자열 존재 유무 확인 가능

ex)

>>> 'means' in t

True

>>> 'mean' in t

True

>>> 'man' in t

False

'Computers > Language python' 카테고리의 다른 글

procedure  (0) 2012.03.14
url 링크 얻기  (0) 2012.03.14
web crawler - extract link  (0) 2012.03.14
파이썬 문자열 string find  (0) 2012.03.14
파이썬 설치하기  (0) 2012.03.14