Notice
Recent Posts
Recent Comments
«   2024/10   »
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
27 28 29 30 31
10-10 20:16
Archives
Today
Total
관리 메뉴

Developer_Neo

[python] 문자열 연산자 및 함수, 메소드 본문

프로그래밍/Python

[python] 문자열 연산자 및 함수, 메소드

_Neo_ 2022. 1. 16. 12:44
반응형

문자열

연산자

  1. +
  2. *
  3. in, not in
  4. del

+ 문자열은 immutable자료형으로 수정이 불가하다 ex) s[2]='b' - (X)

 ''' + '''
>>> first_name = 'Hyunho' 
>>> last_name = 'Jo' 
>>> full_name = first_name + ' ' + last_name 
>>> full_name
'Hyunho Jo'

 ''' * ''''
>>> a = 'Hello' 
>>> a * 3 
'HelloHelloHello' 
>>> greeting 
'Hello'

>>> a = 'Hello' 
>>> a *= 3 
>>> a # a=a*3
'HelloHelloHello' 

''' in, not in  '''
>>> words = 'abcdef' 
>>> 'b' in words 
True
>>> 'v' in words 
False
>>> 'fg' not in words 
True

''' del '''
>>> name = 'Hyunho'
>>> del name[2]
'''
Traceback (most recent call last):
  File "<pyshell#19>", line 1, in <module>
    del name[2]
TypeError: 'str' object doesn't support item deletion
왜냐하면 문자열은 immutable자료형으로 인덱싱으로 하는 수정 삭제에 대해서 불가하다. 
'''
>>> name
'''
Traceback (most recent call last):
  File "<pyshell#21>", line 1, in <module>
    name
NameError: name 'name' is not defined
통째로 삭제는 가능하다
'''

함수

len(), max(), min(), sorted(), reversed()

sum()은 적용할 수 없다.

len(S) 문자열 S의 길이 반환
max(S) 문자열 S의 문자들 중 ASCII코드 값이 가장 큰 문자 반환
min(S) 문자열 S의 문자들 중 ASCII코드 값이 가장 작은 문자 반환
sorted(S) 문자열 S의 문자들을 ASCII코드 값으로 정렬하여 리스트로 반환
reversed(S) 문자열 S를 역순으로 바꾸어준다. reversed객체를 반환

reversed객체를 눈으로 보고 싶다면 list함수나 tuple함수등으로 변환한뒤에 봐야한다.

>>> language = 'python' 
>>> sorted(language) # 아스키코드는 소문자>대문자>스페이스 순서 아스키 코드값 오름순으로 리스트로 출력
['h', 'n', 'o', 'p', 't', 'y'] 

>>> sorted(language, reverse=True) # reverse=True 추가하면 내림차순 정렬
['y', 't', 'p', 'o', 'n', 'h']

>>> R=reversed(language)
>>> print(R)
<reversed object at 0x000001B052D820A0>
>>> L=list(R)
>>> print(L)
['n', 'o', 'h', 't', 'y', 'p']

 

메소드

>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', 
'__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', 
'__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', 
'__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 
'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 
'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 
'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 
'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 
'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 
'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

 

  1. center()
    '''
    인수1개 문자열.center(문자열 폭)
    인수2개 문자열.cneter(문자열 폭, 빈 칸을 채울문자) 안쓸시에 디폴드 값 공백
    반환값 -> 가운데로 정렬한 문자열
    '''
    >>> x='python'
    >>> y=x.center(10)
    >>> x
    'python'
    >>> y
    '  python  '
    >>> y=x.center(10,'@')
    >>> y
    '@@python@@'
    >>> y=x.center(5,'$')
    >>> y
    'python'​
  2. ljust() / rjust()
    >>> x='python'
    >>> y=x.ljust(10)
    >>> x
    'python'
    >>> y
    'python    '
    >>> y=x.ljust(10,'+')
    >>> y
    'python++++'
    
    >>> y=x.rjust(10)
    >>> y
    '    python'
    >>> y=x.rjust(10,'$')
    >>> y
    '$$$$python'​
  3. format()
    ''' {}가 포함된 문자열에 적용 '''
    >>> x='I like {} and {}'
    >>> x.format('apple','strawberry')
    'I like apple and strawberry'
    
    ''' {숫자}가 포함된 문자열에 적용  '''
    >>> x='I like {0} and {1}. {0} is my favorite one'
    >>> x.format('Lemon','choolate')
    'I like Lemon and choolate. Lemon is my favorite one'
    
    '''  {변수}가 포함된 문자열에 적용  '''
    >>> x='{name} is {age} years old'
    >>> x.format(name='HyunHo',age=23)
    'HyunHo is 23 years old'
  4. format_map()
    ''' 이 메소드의 인수는 사전형태이어야한다. '''
    
    >>> v={'a':10, 'b':20, 'c':30}
    >>> '{a}, {b}, {c}'.format_map(v)
    '10, 20, 30'
  5. 문자열 결합/분리하기 – join(), split(), rsplit(), splitlines()
  6. 문자열에서 불필요한 문자 떼어내기 - strip(), rstrip(), lstrip()
  7. 문자열 분할하기 – partition(), rpartition()
  8. 각 문자를 대체 – maketrans(), translate()
  9. 문자열 대체 – replace()
  10. 문자열에 0으로 채우기 – zfill()

 

반응형
Comments