Python/ETC

[python] 파이썬 문자열 함수 (String Methods)

꼰대 2021. 5. 16. 20:37

1. capitalize()

- 문자열 중 첫번째 캐릭터를 대문자로 변경

- 참고 : https://www.w3schools.com/python/ref_string_capitalize.asp

>> str = 'hello world'

>> x = str.capitalize()

>> print(x)

Hello world


2. casefold()

- 문자열을 유니코드로 변환한 후 소문자로 변경, lower() 보다 더 많은 문자열 변환 가능

- 참고 : https://www.w3schools.com/python/ref_string_casefold.asp

>> str = "abcAbCdßß"

>> x = str.casefold()

>> y = str.lower()

>> print(f'casefold() : {x}')

>> print(f'lower() : {y}')

casefold() : abcabcdssss
lower() : abcabcdßß


3. center(length, character)

- 총 문자열의 길이를 첫번째 인자의 숫자 만큼 확보 후 대상 문자열을 중앙 정렬

- 만약 두번째 인자 캐릭터가 있을 경우 중앙 정렬 후 앞뒤로 있는 공백을 해당 캐릭터로 채움

- 참고 : https://www.w3schools.com/python/ref_string_center.asp

>> str = 'Hello'

>> x = str.center(30)

>> print(x)

>> y = str.center(30, '-')

>> print(y)

               Hello
------------Hello-------------


4. count(value, start, end)

- 문자열 중 첫번째 받은 문자열을 찾아 수량을 반환

- 두번째 인자는 찾을 문자열의 시작 index

- 세번째 인자는 찾을 문자열의 마지막 index

- 참고 : https://www.w3schools.com/python/ref_string_count.asp

>> str = "I love apples, apple are my favorite fruit, apple!"

>> x = str.count("apple")

>> print(x)

3

 

>> # 찾는 범위 les, apple are

>> y = str.count("apple", 10, 24)

>> print(y)

1


5. encode()

- 문자열을 UTF-8로 encode

- 참고 : https://www.w3schools.com/python/ref_string_encode.asp

>> str1 = "My name is Ståle"

>> x = str1.encode()

>> print(x)

b'My name is St\xc3\xa5le'

 

>> str2 = 'My name is ggondae'

>> y = str2.encode()

>> print(y)

b'My name is ggondae'

 

>> str3 = '나의 이름은 꼰대'

>> z = str3.encode()

>> print(z)

b'\xeb\x82\x98\xec\x9d\x98 \xec\x9d\xb4\xeb\xa6\x84\xec\x9d\x80 \xea\xbc\xb0\xeb\x8c\x80'


6. endswith(value, start, end)

- (switch 아님) 문자열의 마지막 문자가 첫번째 입력 받은 인자와 동일하다면 True, 아니면 False 반환

- 두번째 인자는 찾을 문자열의 시작 index

- 세번째 인자는 찾을 문자열의 마지막 index

- 참고 : https://www.w3schools.com/python/ref_string_endswith.asp

>> str = "Hello, welcome to my world."

>> x = str.endswith(".")

>> print(x)

True

 

>> str = "Hello, welcome to my world."

>> x = str.endswith("my world.", 5, 11)

>> print(x)

False


7. expandtabs(tabsize)

- 문자열 내 탭을 빈 공간으로 삭제한 문자열 반환

- 인자로 탭 사이즈를 받을 수 있으면 기본값은 8

- 참고 : https://www.w3schools.com/python/ref_string_expandtabs.asp

>> str = "H\te\tl\tl\to"

>> x =  str.expandtabs()

>> y = str.expandtabs(4)

>> print(x)

>> print(y)

H       e       l       l       o
H   e   l   l   o


8. find(value, start, end)

- 문자열 내 첫번째 인자 값과 동일한 문자나 문자열의 index를 반환, 없으면 -1 반환

- 두번째 인자는 찾을 문자열의 시작 index

- 세번째 인자는 찾을 문자열의 마지막 index

- 참고 : https://www.w3schools.com/python/ref_string_find.asp

>> str = "Hello, welcome to my world."

>> x = str.find("w")

>> print(x)

7

 

>> y = str.find("q")

>> print(y)

-1

 

>> z = str.find("to")

>> print(z)

15


9. format(value1, value2 ...)

- 문자열의 {}에 값 입력, 인자에 index를 부여할 수 있음

- 참고 : https://www.w3schools.com/python/ref_string_format.asp

>> print('My name is {}, I'm {}'.format('ggondae', 36))

My name is ggondae, I'm 36

 

>> print('My name is {1}, I'm {0}'.format(36, 'ggondae'))

My name is ggondae, I'm 36


10. index(value, start, end)

- 문자열 내 첫번째 인자 값과 동일한 문자나 문자열의 index를 반환, 없으면 Exception 발생

- 두번째 인자는 찾을 문자열의 시작 index

- 세번째 인자는 찾을 문자열의 마지막 index

- 참고 : https://www.w3schools.com/python/ref_string_index.asp

>> str = "Hello, welcome to my world."

>> x = str.find("w")

>> print(x)

7

 

>> z = str.find("to")

>> print(z)

15

 

>> y = str.find("q")

>> print(y)

Exception has occurred: ValueError
substring not found


11. isalnum()

- 문자열 내 영문 혹은 숫자만 있으면 True, 아니면 False (한글 무시)

- 참고 : https://www.w3schools.com/python/ref_string_isalnum.asp

>> a = 'comPany12'

>> b = 'company 12'

>> c = '안녕하세요12'

>> d = '안녕하세요hi'

>> print(a.isalnum())

>> print(b.isalnum())

>> print(c.isalnum())

>> print(d.isalnum())

True

False

True

True


12. isalpha()

- 문자열이 문자로 이루어져 있으면 True, 아니면((space)!#%&?numberic) False 반환

- 참고 : https://www.w3schools.com/python/ref_string_isalpha.asp

>> str = "CompanyX"

>> x = str.isalpha()

>> print(x)

True

 

>> str = "안녕하세요"

>> y = str.isalpha()

>> print(y)

True

 

>> str = "CompanyX10"

>> z = str.isalpha()

>> print(z)

False


13. isdecimal()

- 유니코드로 이루어진 문자열이 10진수라면 True, 아니면 False

- 참고 : https://www.w3schools.com/python/ref_string_isdecimal.asp

>> # unicode for 3

>> str = '\u0033'

>> x = str.isdecimal()

>> print(x)

True

 

>> # unicode for G

>> str = '\u0047'

>> y = str.isdecimal()

>> print(y)

False


14. isdigit()

- 문자열이 숫자로 이루어져 있으면 True, 아니면 False

- 참고 : https://www.w3schools.com/python/ref_string_isdigit.asp

>> str = '2342343'

>> x = str.isdecimal()

>> print(x)

True

 

>> str = 'a45345'

>> y = str.isdecimal()

>> print(y)

False


15. isidentifier()

- 문자열이 python에서 사용될 수 있으면 True, 사용 불가능하면 False

- 사용 가능 시작 문자 : a~z, A~Z, _

- 사용 불가능 시작 문자 : 0~9, (space)

- 문자열 내 사용 불가능 문자 : (space)

- 참고 : https://www.w3schools.com/python/ref_string_isidentifier.asp

>> a = "MyFolder"

>> b = "demo002"

>> c = "2bring"

>> d = "my demo"

>> print(a.isidentifier())

>> print(b.isidentifier())

>> print(c.isidentifier())

>> print(d.isidentifier())

True

True

False

False


16. islower()

- 문자열 내 영문이 모두 소문자이면 True, 아니면 False

- 영문 캐릭터만 체크하고 나머지는 무시

- 참고 : https://www.w3schools.com/python/ref_string_islower.asp

>> a = 'Hello world!'

>> b = 'hello 123'

>> c = 'mynameisPeter'

>> d = '안녕하세요hi'

>> print(a.islower())

>> print(b.islower())

>> print(c.islower())

>> print(d.islower())

False

True

False

True


17. isnumeric()

- 문자열 내 양수형 정수만 있는 경우 True, 아니면 False

- 참고 : https://www.w3schools.com/python/ref_string_isnumeric.asp

>> a = '12345'

>> b = '100 12'

>> c = '12km'

>> d = '-1'

>> e = '0.5'

>> print(a.isnumeric())

>> print(b.isnumeric())

>> print(c.isnumeric())

>> print(d.isnumeric())

>> print(e.isnumeric())

True

False

False

False

False


18. isprintable()

- 문자열이 출력 가능하면 True, 아니면 False

- 참고 : https://www.w3schools.com/python/ref_string_isprintable.asp

>> a = '\u0030'  # unicode for 0

>> b = '\u0090'  # unknown unicode

>> c = 'Hello! Are you #1?'

>> d = 'Hello!\nAre you #1?'  # include \n

>> print(a.isprintable())

>> print(b.isprintable())

>> print(c.isprintable())

>> print(d.isprintable())

True

False

True

False


19. isspace()

- 문자열이 모두 공백 (space)이면 True, 아니면 False

- 참고 : https://www.w3schools.com/python/ref_string_isspace.asp

>> a = '       '

>> b = '   s   '

>> print(a.isspace())

>> print(b.isspace())

True

False


20. istitle()

- 문자열 내 공백으로 구분된 모든 캐릭터의 첫글자가 대문자면 True, 아니면 False

- 참고 : https://www.w3schools.com/python/ref_string_istitle.asp

>> a = "HELLO, AND WELCOME TO MY WORLD"

>> b = "Hello, and welcome to My World!"

>> c = "Hello, My Name Is Ggondae"

>> d = "22 Namesee"

>> e = "This Is %'!?"

>> print(a.istitle())

>> print(b.istitle())

>> print(c.istitle())

>> print(d.istitle())

>> print(e.istitle())

False

False

True

True

True


21. isupper()

- 문자열 내 공백으로 구분된 모든 캐릭터가 모두 대문자면 True, 아니면 False

- 참고 : https://www.w3schools.com/python/ref_string_isupper.asp

>> a = "Hello World!"

>> b = "hello 123"

>> c = "HELLO 123"

>> d = "MY NAME IS PETER"

>> print(a.isupper())

>> print(b.isupper())

>> print(c.isupper())

>> print(d.isupper())

False

False

True

True


22. join(iterable)

- 첫번째 인자로 받은 반복 가능한 object의 데이터를 문자열을 구분자로 하나의 String을 반환

- 딕션너리 타입은 key값을 반환

- 참고 : https://www.w3schools.com/python/ref_string_join.asp

>> list = ['John', 'Peter', 'Vicky']

>> x = '/'.join(list)

>> print(x)

John/Peter/Vicky

 

>> dict = {'name1':'John', 'name2':'Peter', 'name3':'Vicky'}

>> y = ' VS '.join(dict)

>> print(y)

name1 VS name2 VS name3


23. ljust(length, character)

- 문자열의 총 길이는 첫번째 인자로 받은 길이만큼 확보 후 좌측 정렬

- 나머지 빈 공간은 두번째 인자로 받은 character로 채움

- 두번째 인자가 없으면 기본값으로 공백 (space)

- 참고 : https://www.w3schools.com/python/ref_string_ljust.asp

>> str = 'banana'

>> x = str.ljust(10)

>> print(f'{x}는 제가 제일 좋아합니다.')

banana    는 제가 제일 좋아합니다.

 

>> str = 'banana'

>> x = str.ljust(10, '#')

>> print(f'{x}는 제가 제일 좋아합니다.')

banana####는 제가 제일 좋아합니다.


24. lower()

- 문자열을 모두 소문자로 변환

- 참고 : https://www.w3schools.com/python/ref_string_lower.asp

>> str = 'Banana IS gooD!'

>> x = str.lower()

>> print(x)

banana is good!


25. lstrip(characters)

- 문자열의 좌측 공백을 자르고 반환

- 첫번째 인자로 문자를 받으면 문자열 처음부터 인자로 받은 문자가 안나올 때까지 자르고 반환

- 참고 : https://www.w3schools.com/python/ref_string_lstrip.asp

>> str = '     banana     is good'

>> x = str.lstrip()

>> print(x)

banana     is good

 

>> str = ',,ssaaww..banana..,,aassww'

>> y = str.lstrip(',.asw')

>> print(y)

banana..,,aassww

 

>> str = 'my     banana     is good'

>> z = str.lstrip()

>> print(z)

my     banana     is good


26. maketrans(x, y, z), translate(table)

- 문자열을 치환할 수 있는 딕션너리 형태의 테이블 생성 {'치환 대상 문자의 ascii값':'치환 할 문자의 ascii값'}

- 실제 치환은 translate() 함수를 사용

- 첫번째 인자만 받을 경우 해당 인자의 타입은 딕션너리 형태의 {'치환 대상 문자의 ascii값':'치환 할 문자의 ascii값'}

- 첫번째 인자, 두번째 인자를 받을 경우 모두 문자타입으로 받으며 해당 문자의 ascii값을 딕션너리 형태로 저장

- 세번째 인자까지 모두 받을 경우 원본 문자열 중 세번째 인자와 동일한 문자는 삭제 (원본 문자열 : 치환 이전 문자열)

- 참고 : https://www.w3schools.com/python/ref_string_maketrans.asp

>> # chr(83) == 'S'

>> # chr(80) == 'P'

 

>> str = 'Hello Sam!'

>> dict = {83:80}

>> table = str.maketrans(dict)

>> x = str.translate(table)

>> print(x)

Hello Pam!

 

>> table = str.maketrans('S', 'P')

>> print(table)

>> # {83:80}

>> y = str.translate(table)

>> print(y)

Hello Pam!

 

>> str = 'Hi Sam!'

>> table = str.maketrans('mSa', 'eJo')

>> print(table)

>> # {109: 101, 83: 74, 97: 111}

>> z = str.translate(table)

>> print(z)

Hi Joe!

 

>> str = 'Good night Sam!'

>> table = str.maketrans('mSa', 'eJo', 'odnght')

>> print(table)

>> # {109: 101, 83: 74, 97: 111, 111: None, 100: None, 110: None, 103: None, 104: None, 116: None}

>> a = str.translate(table)

>> print(a)

G i Joe!


27. partition(value)

- 문자열 내 첫번째 인자로 받은 값을 찾아 아래와 같은 포멧의 튜플 반환

- ('인자 값 이전의 문자열', '인자 값', '인자 값 이후의 문자열')

- 이전 및 이후 문자열은 공백 (space) 포함

- 인자 값과 동일한 값이 없다면 ('문자열', '', '')을 반환

- 참고 : https://www.w3schools.com/python/ref_string_partition.asp

>> str = 'I could eat bananas all day'

>> x = str.partition('banana')

>> print(x)

('I could eat ', 'banana', 's all day')

 

>> y = str.partition('apple')

>> print(y)

('I could eat bananas all day', '', '')


28. replace(oldvalue, newvalue, count)

- 문자열 내 첫번째 인자로 받은 값을 두번째 인자로 받은 값으로 변경

- 세번째 인자가 있을 경우 문자열 앞에서부터 인자 수만큼 변경

- 참고 : https://www.w3schools.com/python/ref_string_replace.asp

>> str = 'one one was a race horse, two two was one too.'

>> x = str.replace('one', 'three')

>> print(x)

three three was a race horse, two two was three too.

 

>> y = str.replace('one', 'three', 2)

>> print(y)

three three was a race horse, two two was one too.


29. rfind(value, start, end), rindex(value, start, end)

- 문자열 내 첫번째 인자로 받은 문자를 문자열 오른쪽부터 검색하여 index 반환

- 두번째 인자는 찾을 문자열의 오른쪽 시작 index

- 세번째 인자는 찾을 문자열의 오른쪽부터 마지막 index

- rfind()와 rindex()는 거의 같음

- rindex()와 다른점은 찾는 값이 없을 때 rfind()는 -1을 반환하고 rindex()는 Exception 발생

- 참고 : https://www.w3schools.com/python/ref_string_rfind.asp

>> str = 'Hello, welcome to my world.'

>> x = str.rfind('e')

>> print(x)

13

 

>> y = str.rindex('e', 5, 10)

>> print(y)

8

 

>> z = str.rfind('q')

>> print(z)

-1

 

>> a = str.rindex('q')

>> print(a)

Exception has occurred: ValueError
substring not found


30. rjust(length, character)

- 문자열의 총 길이는 첫번째 인자로 받은 길이만큼 확보 후 우측 정렬

- 나머지 빈 공간은 두번째 인자로 받은 character로 채움

- 두번째 인자가 없으면 기본값으로 공백 (space)

- 참고 : https://www.w3schools.com/python/ref_string_rjust.asp

>> str = 'banana'

>> x = str.rjust(10)

>> print(f'{x}는 제가 제일 좋아합니다.')

    banana는 제가 제일 좋아합니다.

 

>> str = 'banana'

>> y = str.rjust(10, '#')

>> print(f'{y}는 제가 제일 좋아합니다.')

####banana는 제가 제일 좋아합니다.


31. rpartition(value)

- 문자열 내 첫번째 인자로 받은 값을 찾아 아래와 같은 포멧의 튜플 반환

- ('인자 값 이전의 문자열', '인자 값', '인자 값 이후의 문자열')

- 이전 및 이후 문자열은 공백 (space) 포함

- 인자 값과 동일한 값이 없다면 ('', '', '문자열')을 반환

- 참고 : https://www.w3schools.com/python/ref_string_rpartition.asp

>> str = 'I could eat bananas all day'

>> x = str.partition('banana')

>> print(x)

('I could eat ', 'banana', 's all day')

 

>> y = str.partition('apple')

>> print(y)

('', '', 'I could eat bananas all day')


32. rsplit(separator, maxsplit)

- 문자열을 분리하여 리스트로 반환하며 첫번째 인자가 없을 경우 공백 (space)로 구분

- 첫번째 인자로 구분자 문자를 받을 경우 해당 구분자로 문자열을 분리하여 리스트로 반환

- 두번째 인자가 있을 경우 리스트의 총 요소 수는 두번째 인자 + 1이 되며 문자열 맨 우측 문자부터 두번째 인자만큼 저장 후 나머지 문자는 합쳐 하나 리스트 요소로 저장 (split()와 반대)

- 참고 : https://www.w3schools.com/python/ref_string_rsplit.asp

>> str = 'apple, banana, cherry, orange'

>> x = str.rsplit()

>> print(x)

['apple,', 'banana,', 'cherry,', 'orange']

 

>> y = str.rsplit(', ')

>> print(y)

['apple', 'banana', 'cherry', 'orange']

 

>> # maxsplit값이 1이므로 리스트의 총 element 수는 2개

>> # 분리한 문자열 중 맨 우측값인 orange만 하나의 element로 두고 나머지는 하나의 element로 저장

>> # 만약 str.rsplit(', ', 2)라면

>> # ['apple, banana', 'cherry', 'orange']

>> z = str.rsplit(', ', 1)

>> print(z)

['apple, banana, cherry', 'orange']


33. rstrip(characters)

- 문자열의 우측 공백을 자르고 반환

- 첫번째 인자로 문자를 받으면 문자열 우측 끝부터 인자로 받은 문자가 안나올 때까지 자르고 반환

- 참고 : https://www.w3schools.com/python/ref_string_rstrip.asp

>> str = 'banana     is good        '

>> x = str.rstrip()

>> print(x)

banana     is good

 

>> str = ',,ssaaww..banana..,,aassww'

>> y = str.rstrip(',.asw')

>> print(y)

,,ssaaww..banan

 

>> str = 'my     banana     is good'

>> z = str.rstrip()

>> print(z)

my     banana     is good


34. split(separator, maxsplit)

- 문자열을 분리하여 리스트로 반환하며 첫번째 인자가 없을 경우 공백 (space)로 구분

- 첫번째 인자로 구분자 문자를 받을 경우 해당 구분자로 문자열을 분리하여 리스트로 반환

- 두번째 인자가 있을 경우 리스트의 총 요소 수는 두번째 인자 + 1이 되며 문자열 처음 문자부터 두번째 인자만큼 저장 후 나머지 문자는 합쳐 하나 리스트 요소로 저장 (rsplit()와 반대)

- 참고 : https://www.w3schools.com/python/ref_string_split.asp

>> str = 'apple, banana, cherry, orange'

>> x = str.split()

>> print(x)

['apple,', 'banana,', 'cherry,', 'orange']

 

>> y = str.split(', ')

>> print(y)

['apple', 'banana', 'cherry', 'orange']

 

>> # maxsplit값이 1이므로 리스트의 총 element 수는 2개

>> # 분리한 문자열 중 맨 좌측값인 apple만 하나의 element로 두고 나머지는 하나의 element로 저장

>> # 만약 str.split(', ', 2)라면

>> # ['apple', 'banana', 'cherry, orange']

>> z = str.split(', ', 1)

>> print(z)

['apple', 'banana, cherry, orange']


35. splitlines(keeplinebreaks)

- 문자열 내 개행문자를 기준으로 분리하여 리스트로 반환

- 개행 문자가 없다면 문자열 하나가 요소로 된 리스트 반환

- 인자값이 True면 개행문자를 포함하여 분리 후 리스트로 반환, 기본값은 False

- 참고 : https://www.w3schools.com/python/ref_string_splitlines.asp

>> str = 'Thank you for the music\nWelcome to the jungle\nMy name is ggondae'

>> x = str.splitlines()

>> print(x)

['Thank you for the music', 'Welcome to the jungle', 'My name is ggondae']

 

>> y = str.splitlines(True)

>> print(y)

['Thank you for the music\n', 'Welcome to the jungle\n', 'My name is ggondae']


36. startswith(value, start, end)

- 문자열의 시작 문자가 첫번째 인자로 받은 값과 같다면 True, 아니면 False

- 두번째 인자는 찾을 문자열의 시작 index

- 세번째 인자는 찾을 문자열의 마지막 index

- 참고 : https://www.w3schools.com/python/ref_string_startswith.asp

>> str = 'Hello, welcome to my world.'

>> x = str.startswith('He')

>> print(x)

True

 

>> y = str.startswith('e')

>> print(y)

False

 

>> z = str.startswith('wel', 7, 20)

>> print(z)

True


37. strip(characters)

- 문자열 앞뒤 공백 제거 후 반환

- 두번째 인자가 있으면 앞위로 해당 인자의 문자와 동일하지 않은 문자를 만날 때까지 삭제 후 반환

- 참고 : https://www.w3schools.com/python/ref_string_strip.asp

>> str = '    b a n a n a    '

>> x = str.strip()

>> print(f'==={str}===')

>> print(f'==={x}===')

===    b a n a n a    ===
===b a n a n a===

 

>> str = '......banana......'

>> y = str.strip('.')

>> print(y)

banana

 

38. swapcase()

- 문자열 내 대문자는 소문자로, 소문자는 대문자로 변환

- 참고 : https://www.w3schools.com/python/ref_string_swapcase.asp

>> str = 'Hello My Name Is PETER'

>> x = str.swapcase()

>> print(x)

hELLO mY nAME iS peter


39. title()

- 문자열 내 공백으로 구분된 문자의 첫번째 문자를 대문자로 변환 (숫자, 기호 무시)

- 참고 : https://www.w3schools.com/python/ref_string_title.asp

>> str = 'Welcome to my 2nd _world'

>> x = str.title()

>> print(x)

Welcome To My 2Nd _World


40. upper()

- 문자열 내 모든 문자를 대문자로 변환

- 참고 : https://www.w3schools.com/python/ref_string_upper.asp

>> str = 'Welcome to my 2nd _world'

>> x = str.upper()

>> print(x)

WELCOME TO MY 2ND _WORLD


41. zfill(len)

- 첫번째 인자로 받은 길이만큼 확보 후 우측 정렬

- 빈 공간은 0으로 채움

- 참고 : https://www.w3schools.com/python/ref_string_zfill.asp

>> a = 'hello'

>> b = 'welcome to the jungle'

>> c = '10.000'

>> print(a.zfill(10))

>> print(b.zfill(10))

>> print(c.zfill(10))

00000hello
welcome to the jungle
000010.000

반응형