문자열
- 문자열의 요솟값은 바꿀 수 있는 값이 아님(immutable한 자료형)
- 슬라이싱을 사용하면 문자열을 변경 가능함
- 문자열 끝에는 \t 가 생략되어 있음
문자열을 만드는 방법_총 4가지
sentence = '나는 소년입니다.'
print(sentence)
sentence2 = "파이썬은 쉬워요"
print(sentence2)
sentence3 = """
가장 깊은 밤에 더 빛나는 별빛
밤이 깊을수록 더 빛나는 별빛
"""
print(sentence3)
sentence4 = '''Life is too short, You need python'''
print(sentence4)
문자열 더해서 연결하기(Concatenation)
head = "Python"
tail = " is fun!"
print(head + tail)
문자열 곱하기
a = "python"
print(a * 2)
문자열 길이 구하기 - len 함수 사용
a = "Life is too short"
print(len(a))
인덱싱
- 변수명[오프셋]는 문자열 안의 특정한 값을 뽑아내는 역할
- 문자열을 뒤에서부터 읽기 위해 마이너스(-) 기호를 붙이는 것
- 0과 -0은 똑같은 것이기 때문에 a[-0]은 a[0]과 똑같은 값을 보여 줌
a = "Life is too short"
print(a[0])
print(a[-1])
슬라이싱
- 단어를 뽑아내는 방법
- 변수명[시작 오프셋:끝 오프셋]를 지정할 때 끝 번호에 해당하는 것은 포함하지 않음
- 변수명[시작 오프셋:끝 오프셋:스텝]
test = "911208-1665716"
print("성별 : " + test[7])
print("년도 : " + test[0:2])
print("월 : " + test[2:4])
print("일 : " + test[4:6])
print("생년월일 : " + test[:6])
print("뒤 7자리 : " + test[7:14])
print("뒤 7자리 : " + test[7:])
print("뒤 7자리(뒤에서 부터) : " + test[-7:-1])
print("뒤 7자리(뒤에서 부터) : " + test[-7:])
test = "abcdefghijklmnopqrstuvwxyz"
print(test[:])
print(test[20:])
print(test[:15])
print(test[-7:])
print("2칸씩 건너뛴 문자 : %s" % test[::2])
print(test[-1::-1])
print(test[::-1])
문자열 처리 함수
python = "Python is Amazing"
print(python.lower())
print(python.upper())
print(python[0].isuppper())
print(len(python))
print(python.replace("Python", "Java"))
index = python.index("n")
print(index)
index = python.index("n", index + 1)
print(index)
index = python.index("Java")
print(index)
print(python.find("Java"))
print(python.count("n")
문자열 포맷
print("나는 %d살 입니다." % 20)
print("나는 %s을 좋아해요." % "파이썬")
print("Apple은 %c로 시작해요." % "A")
print("나는 %s살 입니다." % 20)
print("나는 %s색과 %s색을 좋아합니다." % ("파랑", "주황"))
print("나는 {}살 입니다.".format(20))
print("나는 {}색과 {}색을 좋아합니다.".format("파랑", "주황"))
print("나는 {0}색과 {1}색을 좋아합니다.".format("파랑", "주황"))
print("나는 {1}색과 {0}색을 좋아합니다.".format("파랑", "주황"))
print("나는 {age}살 이며, {color}색을 좋아합니다.".format(age = 20, color = "파랑"))
- 아래 방법은 python 3.6 버전 이상에서 가능
age = 20
color = "파랑"
print(f"나는 {age}살 이며, {color}색을 좋아합니다.")
age = 20
color = "파랑"
print(f"나는 {age}살 이며, {color}색을 좋아합니다.")
age = 20
color = "파랑"
print(f"나는 {age + 1}살 이며, {color}색을 좋아합니다.")
문자 개수 세기(count)
a = "hobby"
print(a.count('b'))
위치 알려주기(find , index)
- 문자열이 없으면 find는 -1을 반환
- 문자열이 없으면 index는 에러 발생
a = "Python is the best choice"
print(a.find('b'))
print(a.index('t'))
문자열 삽입(join)
print(",".join('abcd'))
소문자를 대문자로 바꾸기(upper)
a = "hi"
print(a.upper())
대문자를 소문자로 바꾸기(lower)
a = "HI"
print(a.lower())
첫번째 단어를 대문자로 바꾸기
test = "abcd efgh ijkl"
print(test.capitalize())
모든 단어의 첫글자를 대문자로 바꾸기
test = "abcd efgh ijkl"
print(test.title())
대소문자 변경하기
test = "AbCd Efgh IjKl"
print(test.swapcase())
공백 지우기
왼쪽 공백 지우기(lstrip)
a = " HI "
print(a.lstrip())
오른쪽 공백 지우기(rstrip)
a = " HI "
print(a.rstrip())
양쪽 공백 지우기(strip)
a = " HI "
print(a.strip())
문자열 바꾸기(replace)
- replace(바뀌게 될 문자열, 바꿀 문자열, 바꿀 횟수)
- 마지막 인수를 생략하면 모든 인스턴스를 바꿈
- 문자열 안의 특정한 값을 다른 값으로 치환
a = "Life is too short"
print(a.replace("Life", "Your leg"))
문자열 나누기(split)
- split 함수는 괄호 안에 아무 값도 넣어 주지 않으면 공백(스페이스, 탭, 엔터 등)을 기준으로 문자열을 나눔
- 괄호 안에 특정 값이 있을 경우에는 괄호 안의 값을 구분자로 해서 문자열을 나눔
- 나눈 값은 리스트에 하나씩 들어감
a = "Life is too short"
print(a.split())
b = "a:b:c:d"
print(b.split(':'))
검색과 선택
test = "abcd efgh ijkl"
print(test.startswith('abcd'))
print(test.endswith('ijkl'))
정렬 및 공백
test = "AbCd"
print(test.center(30))
print(test.ljust(30))
print(test.rjust(30))
print("%10s" % 'hi')
print("%-10sjane" % 'hi')
print("{0:<10}".format("hi"))
print("{0:>10}".format("hi"))
print("{0:^10}".format("hi"))
print("{0:=^10}".format("hi"))
print("{0:!^10}".format("hi"))
소수점 표현
print("%0.4f" % 3.123456)
print("%10.4f" % 3.123456)
print("{0:0.4f}".format(3.123456))
print("{0:10.4f}".format(3.123456))
탈출 문자
print("가장 깊은 밤에 더 빛나는 별빛**\n**밤이 깊을수록 더 빛나는 별빛")
print("저는 '아미' 입니다.")
print('저는 "아미" 입니다.')
print("저는 **\"**아미\" 입니다.")
print("c:**\\**User**\\**Desktop**\\**test")
print("Red apple**\r**Pine")
print("Redd\bApple")
print("Red\tApple")
print("{{ and }}".format())