본문 바로가기

Python 문법 & 메서드 (문자열) 본문

개발/Python | Java

Python 문법 & 메서드 (문자열)

자전하는명왕성 2023. 10. 18. 09:53

Python을 공부하게 되면서 알게 된 문법 혹은 메서드 정리한다.

자바스크립트와 같은 기능을 가진 메서드는 소괄호로 표현하였다.

 

""" """ (템플릿 리터럴)

exam = """안
녕
"""

# 안
# 녕

format() 

exam = '{} is {}'.format('a', 'b')
# 'a is b'

slice

exam = 'abcdef'
exam[:3] # abc [0:3] 이므로 0 ~ 2
exam[3:] # def [3:끝] 이므로 3 ~ 끝
exam[3:5] # de

split

exam = 'abcdef'
exam.split() # ['abcdef']
list(exam) # ['a', 'b', 'c', 'd', 'e', 'f']

count

# String.count(target, start, end) 로 사용

exam = 'aacdef'
exam.count('a') # 2
exam.count('a', 1) # 1
exam.count('a', 2, 3) # 0

upper & lower & table & swapcase & capitalize

exam = 'aBcDeF'

print(exam.upper()) # ABCDEF 모두 대문자
print(exam.lower()) # abcdef 모두 소문자
print(exam.title()) # Abcdef 맨앞 글자 대문자
print(exam.swapcase()) # AbCdEf 대소문자 반전
print(exam.capitalize()) # Abcdef 첫문자만 대문자, 나머지 소문자

find & rfind (indexOf, lastIndexOf)

exam = 'abcdefa'

print(exam.find('a')) # 0  맨앞에서부터 요소 발견 시 해당 index 반환 
print(exam.rfind('a')) # 6  맨뒤에서부터 요소 발견 시 해당 index 반환 
print(exam.find('z')) # -1  없을 시 -1 반환

strip (trip)

exam = '  abc  defa '

print(exam.strip()) # abc  defa  좌우 공백 제거 후 반환

replace (replaceAll)

exam = 'abcdefa'

print(exam.replace('a','@')) # @bcdef@  첫 인자와 같은 값을 두 번째 인자값으로 변경

in & not in 

exam = 'abcdef'
print('a' in exam) # True 있는지 파악
print('@' in exam) # False 
print('a' not in exam) # False 없는지 파악

isdigit & isalpha

# isdigit() => 문자열이 수인지 아닌지 파악
# isalpha() => 문자열이 알파벳인지 아닌지 파악
exam1 = 'abcdef'
exam2 = '123'
print(exam1.isdigit()) # False  
print(exam2.isdigit()) # True
print(exam1.isalpha()) # True
print(exam2.isalpha()) # False

'개발 > Python | Java' 카테고리의 다른 글

Python 문법 & 비트마스킹  (0) 2023.11.17
Python 문법 & 메서드 (리스트)  (0) 2023.10.19
오버플로우  (0) 2023.06.12
Comments