본문 바로가기
Python/Python

[Python] 문자열 메서드

by 기록하는_사람 2022. 9. 22.

문자열 메서드 - .split( )

📌 문자열.split(문자)

: 문자열을 입력한 '문자' 기준으로 자른 후 리스트로 반환.

s = ("Hi-Nice-to-meet-you")
print(s.split("-"))

# ['Hi', 'Nice', 'to', 'meet', 'you']

 

📌 .split( )을 할 경우, 이스케이프 문자를 포함한 공백에 따라 문자열을 자름.

s = ("Hi\nMy name is")
print(s.split())

# ['Hi', 'My', 'name', 'is']

 

문자열 메서드 - .replace( )

📌 문자열.replace(A, B)

: 문자열 안의 A를 B로 바꿔 문자열 반환.

s = "banana".replace('n', 'b')
print(s)

# bababa

 

문자열 메서드 - .count( )

📌 문자열.count(a)

: 문자열 안의 a의 개수 반환.

s = 'I want to know our problem, blood type or DNA? (If you know this) Friends see my feed and worry, do you babe? Yeah Been waiting for your call every night But I cant wait no more Dialing you-hoo-hoo Sorry, darling you You know, without you, Im so lonely When youre not here, 911 calling Into your heat again, Im diving Darling you, darling you, baby'

print(s.count('darling'))  # 2

 

문자열 메서드 - .isalpha( )

📌 문자열.isalpha( )

: 문자열이 알파벳으로 이루어져 있으면 True, 아니면 False를 반환.

li = ['abcdefgh', 'abcd1234', 'abcd!@#']

for i in li:
    if i.isalpha():
        print(i)    # abcdefgh

 

문자열 메서드 - .isnumeric( )

📌 문자열.isnumeric( )

: 문자열이 숫자로 이루어져 있으면 True, 아니면 False를 반환.

li = ['abcdefgh', 'abcd1234', 'abcd!@#', '12345']

for i in li:
    if i.isnumeric():
        print(i)    # 12345

 

문자열 메서드 - .strip( )

📌 문자열.strip( )

: 양쪽 공백, 이스케이프 문자 제거 후 반환.

s = '\nHi Hello Nice to meet you  '

print(s.strip())    # Hi Hello Nice to meet you

 

문자열 메서드 - .upper( )

📌 문자열.upper( )

:  모든 글자를 대문자로 바꾼 후 반환.

s = 'Hi Hello Nice to meet you'

print(s.upper())    # HI HELLO NICE TO MEET YOU

 

문자열 메서드 - .lower( )

📌 문자열.lower( )

: 모든 글자를 소문자로 바꾼 후 반환.

s = 'Hi Hello Nice to meet you'

print(s.lower())    # hi hello nice to meet you

 

문자열 메서드 - .zfill(n)

📌 문자열.zfill(n)

: n자리수 중 공백을 0으로 채움.

s = "1"

print(s.zfill(3)) # 001

'Python > Python' 카테고리의 다른 글

[Python] 문자열 대소 비교 | 유니코드  (0) 2022.09.23
[Python] if ~ in, if ~ not in  (0) 2022.09.22
[Python] 문자열 | 문자열 index | 슬라이싱  (0) 2022.09.22
[Python] 슬라이싱  (0) 2022.09.22
[Python] index와 indexing  (0) 2022.09.22

댓글