07 string mehtod

String Method

  • 파이썬의 string은 객체이므로 문자를 다루는 여러 메소드들이 존재함
  • 중요 메소드들을 살펴보면 다음과 같다.
    • 문자열의 변환: upper(), lower(), swapcase(), capitalize(), title()
    • 문자열의 검색: count(), find(), index(), startwitch()
    • 분리, 결합, 치환:split(),splitlines(),join(), replace(), strip()
    • 문자열 판별:isdigit(), isalpha(), isspace()
    • 정렬과 채움:center(), rjust(), ljust(), zfill()
  • 파이썬에서 String은 객체이므로 dir(str) 명령어를 입력하면 사용가능함 메소드들을 확인할 수 있다.

문자열의 변환

In [54]:
print("Bother Sister".upper())
print("Bother Sister".capitalize())
print("bother sister".title())
BOTHER SISTER
Bother sister
Bother Sister

문자열 분리, 결합, 치환

In [49]:
print("---split---")
print('010-12x4-56y8'.split('-'))
print('010-12x4-56y8'.split('-', 1))
a = '010-12x4-56y8'.split('-')
print(a)
print("---join---")
print("".join(a))
print(" ".join(a))
print("-".join(a))
print("---strip---")
print('---010 12x4 56y8--'.strip('-'))
print('uu010 12x4 56y8UU'.strip('uu'))
print("---replace---")
print('---010-12x4-56y8--'.replace('-',''))
print('---010-12x4-56y8--'.replace('-','**'))
---split---
['010', '12x4', '56y8']
['010', '12x4-56y8']
['010', '12x4', '56y8']
---join---
01012x456y8
010 12x4 56y8
010-12x4-56y8
---strip---
010 12x4 56y8
010 12x4 56y8UU
---replace---
01012x456y8
******010**12x4**56y8****

문자열의 검색

In [ ]:
"To day is the greatest day. I've ever known".count("day")
"To day is the greatest day. I've ever known".startswith("To")
"To day is the greatest day. I've ever known".find("day")
In [67]:
"To day is the greatest day. I've ever known".rfind("dae")
Out[67]:
-1
In [64]:
"great" in "To day is the greatest day. I've ever known"
Out[64]:
True

문자열 판별

In [71]:
print("12ab".isalnum())
print("aa".isdigit())
print("aa bb".isspace())
True
False
False


© 2017. All rights reserved.

Powered by ZooFighter v0.12