Contents
- upper(),lower()
- strip()
- split(), join()
- index(), find()
- startswith(), endswith()
- ord(),chr()
- 실습 예제 1
- 실습 예제 2
1. upper(), lower()
upper() : 문자열을 전부 대문자로 만드는 함수
lower() : 문자열을 전부 소문자로 만드는 함수
e.g.
a='python'
a.upper() # 'PYTHON'
a # 'python'
c.f. 문자열 메서드는 문자열을 직접 변경시키지 않는다
2. strip()
ㄴ 좌우 공백을 제거하는 함수
a= ' Hello Pyhton '
a.strip() # 'Hello Python'
3. split(), join()
split()
e.g.
data= "수박,복숭아,자두,멜론"
data.split(",") # ['수박','복숭아','자두','멜론']
join()
e.g.
data=['A','B','C','D']
",".join(data) # "A,B,C,D"
4. index(),find()
index() : 주어진 문자열을 찾으면 원본 문자열 내의 index 추출
e.g.
str= "hello python"
str.index('l') # 2
str.find('lo') # 3 시작부분에 해당하는 index 추출
str.find('xx') ## -1 : 찾지 못하면 -1 추출
5. startswith(), endswith()
문자열이 특정 문자열로 시작/종료하는 지 여부를 표시
e.g.
str="https://www.tistory.com"
str.startswith("http") # True
str.endswith(".com") # True
str.endswith(".net") # False
6. ord(),chr()
ord() : 문자의 코드값 반환
chr() : 코드의 문자값 반환
e.g.
ord('A') # 65
chr(65) # 'A'
e.g. 알파벳 개수 구하기 예제
ord('Z')-ord('A')+ 1 # 26
실습 예제 1
from contextlib import nullcontext
# *******************************
# 가장 긴 단어 찾기 위한 longestWord 함수를 작성할 것
data = [
"I am a Student", # -> Student
"That elephant is big", # -> elephant
"She loves cat very much", # -> loves
]
print(list(map(longestWord, data)))
# 출력: ['Student', 'elephant', 'loves']
답
def longestWord(sentence):
temp= sentence.split()
longest=temp[0]
for word in temp:
if len(word)>=len(longest):
longest=word
return longest
실습 예제 2
# *******************************
# 문장에서 각 단어 첫글자만 대문자 만들기
#
data = [
"i am a PROGRAMMER", # -> I Am A Programmer
"THAT ELEPHANT IS BIG", # -> That Elephant Is Big
]
print(list(map(letterCapitalize, data)))
답)
def letterCapitalize(sentence):
result=[]
temp=sentence.lower().split()
for word in temp:
if len(word)>1:
result.append(word[0].upper()+word[1:])
else:
result.append(word[0].upper())
final=" ".join(result)
return final'python' 카테고리의 다른 글
| BootCamp Day02 Python ② 문자열 다루기 (0) | 2026.05.21 |
|---|---|
| BootCamp Day01 – Python 기초 다시 복습하기 (0) | 2026.05.20 |
| 파이썬 상속 / self / __init__ 개념 정리 (0) | 2026.05.02 |
| 파이썬으로 CSV 파일 분석하는 방법 (타이타닉 생존자 수 예제) (3) | 2025.08.08 |
| 정규 표현식 (1) | 2025.08.05 |