문자열 관련 함수

✒️ 2025-05-19 10:31 내용 수정

Do it! 점프 투 파이썬(2017년 발행) 내용을 정리


count

>>> a = "effort"
>>> a.count('f')
2

find

>>> a = "Hello World"
>>> a.find("H")
0
>>> a.find("h")
-1
>>> a.find("l")
2
>>> a.find("lo")
3

index

>>> a = "Hello World"

>>> a.index("W")
6

>>> a.index("h")
Traceback (most recent call last):
  File "<python-input-110>", line 1, in <module>
    a.index("h")
    ~~~~~~~^^^^^
ValueError: substring not found

join

>>> "|".join("test")
't|e|s|t'

>>> "|".join(['a','p','p','l','e'])
'a|p|p|l|e'

upper와 lower

>>> a = "hello world"
>>> a.upper()
'HELLO WORLD'

>>> b = "NEXT TIME"
>>> b.lower()
'next time'

공백 제거(lstrip, rstrip, strip)

  1. lstrip() : 왼쪽 공백을 지운다.
>>> a = "     test        "
>>> a.lstrip()
'test        '
  1. rstrip() : 오른쪽 공백을 지운다.
>>> a = "     test        "
>>> a.rstrip()
'     test'
  1. strip() : 양쪽 공백을 모두 지운다.
>>> a = "     test        "
>>> a.strip()
'test'

replace

>>> a = "Music is on"
>>> a.replace("on", "off")
'Music is off'

split

>>> a = "Today is 2025/03/28"

>>> a.split()
['Today', 'is', '2025/03/28']

>>> a.split('/')
['Today is 2025', '03', '28']

문자열의 구성을 확인하는 함수

  1. isalnum() : 문자열이 알파벳 또는 숫자로만 이루어졌다면 True, 아니면 False
>>> "alpha1234".isalnum()
True

>>> "alpha".isalnum()
True

>>> "1234".isalnum()
True

>>> "    alpha1234".isalnum()
False
  1. isalpha() : 문자열이 알파벳으로만 이루어졌다면 True, 아니면 False
>>> "alpha".isalpha()
True

>>> "alpha1234".isalpha()
False

>>> "    alpha1234".isalpha()
False
  1. isdecimal() : 문자열이 정수 면 True, 아니면 False
    • 순수 10진수(0~9)거나 전각 숫자(1 2 3) 포함 되어 있는지 확인한다.
    • 전각 문자 : 동아시아에서 사용하는 문자폭이 넓은 문자로, 유니코드 범위가 U+FF10~U+FF19 이다.
    • 일반적으로 사용하는 숫자의 유니코드 범위는 ASCII U+0030~U+0039 이다.
>>> "1234".isdecimal()
True

>>> "1.23".isdecimal()
False
  1. isdigit() : 문자열이 숫자로 볼 수 있는 문자(숫자, 전각 숫자, 지수)로 이루어졌다면 True, 아니면 False
    • 소수점 .이나 분수 기호 %를 포함하면 False로 뜬다.
>>> "1234".isdigit()
True

>>> "1.23".isdigit()
False
print("²".isdigit()) # True
print("Ⅳ".isdigit()) # False
print("3.14".isdigit()) # False
print("10".isdigit()) # True
print("Ⅳ".isdigit()) # False
print("Ⅳ".isnumeric()) # True
  1. isnumeric() : 문자열이 숫자로 볼 수 있는 문자(숫자, 전각 숫자, 지수, 로마자, 분수) 로 이루어졌다면 True, 아니면 False
print("1234".isnumeric()) # True
print("²".isnumeric()) # True
print("Ⅳ".isnumeric()) # True
print("½".isnumeric()) # True
print("10".isnumeric()) # True
print("3.14".isnumeric()) # False
함수 0-9 전각숫자(10) 지수 로마숫자 분수 소수 음수
isdecimal() ✔️ ✔️
isdigit() ✔️ ✔️ ✔️
isnumeric() ✔️ ✔️ ✔️ ✔️ ✔️
  1. isspace() : 문자열이 공백으로만 되어 있다면 True, 아니면 False
>>> "   ".isspace()
True

>>> "   1".isspace()
False