본문 바로가기

프로그래밍

[python] 문자열 포맷팅, 메서드 사용법

변수에 문자열 선언

a = "hello python"

b = 'start python'

 

두 줄로 작성한 코드 변수에 값 할당하기

c = """hello 

python"""

 

 

문자열 연산

a = 'hello'
b = 'python'

print(a+b)

결과
hellopython

 

a = 'hello'
b = 'python'

print(a + ' ' + b)

결과
hello python

 

a = '*' * 40

print(a)

결과
****************************************

 

문자열 인덱싱

첫 번째 문자열 가져오기

a = "test python string"

print(a[0])

결과
t

 

마지막 문자열 가져오기

a = "test python string"

print(a[-1])

결과
g

 

0번째부터 2글자 가져오기

a = "test python string"

print(a[0:2])

결과
te

 

처음부터 10글자 가져오기

a = "test python string"

print(a[:10])

결과
test pytho

 

3번째부터 마지막까지 가져오기

a = "test python string"

print(a[3:])

결과
t python string

 

문자열 포맷팅

height = 175
a = "내 키는 %d입니다." % height

print(a)

결과
내 키는 175입니다.

 

height = 175.5
weight = 70

a = "내 키는 %f이고 몸무게는 %d입니다." % (height, weight)
print(a)

결과
내 키는 175.500000이고 몸무게는 70입니다.

 

height = 175.5
weight = 70

a = "내 키는 {}이고 몸무게는 {}입니다.".format(height, weight)

print(a)

결과
내 키는 175.5이고 몸무게는 70입니다.

 

a = "숫자 {2}, {1}, {0}".format(1, 2, 3)

print(a)

결과
숫자 3, 2, 1

 

# 파이썬 버전 3.6 이상에서 가능
country = '한국'
name = '홍길동'
age = 20
a = f"난 {country} 사람이고 이름은 {name}이며 나이는 {age} 입니다."

print(a)

결과
난 한국 사람이고 이름은 홍길동이며 나이는 20 입니다.

 

a = "{0:=<30}".format("안녕")
print(a)

결과
안녕============================

 

a = "{0:=>30}".format("하이")
print(a)

결과
============================하이

 

a = "{0:*^30}".format("파이썬")
print(a)

결과
*************파이썬**************

 

a = "*" * 15 + "파이썬" + "*" * 15
print(a)

결과
***************파이썬***************

 

문자열 위치 찾기 메서드 : find, index

temp = "가나다라마바사아자차카타파하"

print(temp.find("라"))

결과
3
#검색하는 문자가 존재하지 않으면 -1 리턴

 

temp = "가나다라마바사아자차카타파하"

print(temp.index("라"))

결과
3
#검색하는 문자가 존재하지 않으면 오류 발생

 

오른쪽에서 부터 문자열 검색 : rfind, rindex

다음 경로에서 jpg 파일명만 가져오기

temp = "/root/image/test.jpg"

print(temp[temp.rfind("/")+1:])

결과
test.jpg

 

구분자 기준으로 문자열 자르기 : split

temp = "/root/image/test.jpg"

print(temp.split("/"))

결과
['', 'root', 'image', 'test.jpg'] #리스트 형태로 반환

 

문자열 치환 : replace

temp = "/root/image/test.jpg"

print(temp.replace("test", "test_new"))

결과
/root/image/test_new.jpg

 

문자열 좌, 우 공백 제거 : strip, rstrip, lstrip

temp = "       안녕하세요."
print(temp)
print(temp.strip())

결과
       안녕하세요.
안녕하세요.

 

문자열 대소문자 치환 : lower, upper

temp = "abcd"
print(temp.upper())
temp = "ABCD"
print(temp.lower())

결과
ABCD
abcd

 

문자열 수 확인 : count, len

temp = "abcdeeeefg"

print(temp.count("e"))
print(temp.count("abc"))
print(len(temp))

결과
4
1
10

 

문자열이 알파벳인지 숫자인지 확인 : 

temp = "abcdeeeefg"
print(temp.isalpha()) #알파벳이면 true, 아니면 false
temp = "123345"
print(temp.isdecimal()) #숫자이면 true, 아니면 false
temp = "123345A"
print(temp.isdecimal())

결과
True
True
False

 

문자열 대소문자 확인 : islower, isupper

temp = "abcdeeeefg"
print(temp.islower()) #소문자이면 True
print(temp.isupper()) #대문자이면 True

결과
True
False

 

str 클래스에서 전체 사용 가능한 메서드 확인 : dir

temp = "123345A"
print(type(temp))
print(dir(str))

결과
<class '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', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip',
'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper',
'zfill']