Python - String Formatting

728x90

String Formatting

Formatting 하는 방법 3가지

  • print(%) 사용
  • print(str.format) 사용
  • print(f.{}{})사용
#print(%s,%d)사용
print("%s가 %d개 있다."%("사과",3)) # %가 변수 connection 하는 인자
사과가 3개 있다

#print(str.format())사용
print("{}가 {}개 있다.".format("사과",3))
사과가 3개 있다.

#print(f{})사용
apple="사과"
apple_n=3
print(f"{apple}가 {apple_n}개 있다.")
사과가 3개 있다

응용편

# 주민등록번호를 출력하는 format 만들기
n=input("주민번호 앞자리를 입력해주세요 :")
if len(n)==6:
    print(f"{n}-******")
else:
    print("주민번호 앞자리 6자리를 입력해주세요")
    
# 숫자가 6자리일 시 ==> 출력문: 000000-******
# 숫자가 6자리 미만일 시 ==> 주민번호 앞자리 6자리를 입력해주세요

문자열 관련 함수

 

  • upper & lower
  • strip()
  • join()
  • replace()
  • split()
#upper() & lower()
a=hi, b=HI
print(a.upper())
HI
print(b.lower()
hi

#strip()
c="     hi   "
c.strip()
hi

#replace()
d="coffee at Ediya"
d.replace("Ediya","Starbucks")
Coffee at Starbucks

#split()
f="test to be splited"
f.split()
['test','to','be','splited']
#split() 안에 리스트 단어를 쓰면 그 단어 제외하고 프린트 가능
f.split("to")
['test','be','splited']

 

 

728x90

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

파이썬의 수 자료형의 연산  (0) 2022.04.27
Python - dictionary  (0) 2021.12.11
Python - tuple & set  (0) 2021.12.11
Python - list ()  (0) 2021.12.09
Python - Integer & String  (0) 2021.12.07