Python

[Python] 문자열 (String)

728x90

쌍따옴표(" ") 또는 홑따옴표(' ') 사용

a="\nHello World"
b='Python is fun'
c="""Life is too short, 

    You need 
    python"""
d='''Life is too short, You need python'''

print(a)
print(b)
print(c)
print(d)
Hello World
Python is fun
Life is too short, 

    You need 
    python
Life is too short, You need python

 

이스케이프 시퀀스

\n : 줄바꿈
\' : '
\" : "
food = "Python's favorite \nfood is perl"
say = '"Python is very easy." he says.'
f = 'Python\'s favorite food is perl'
s = "\"Python is very easy.\" \n he says."

print(food)
print(say)
print(f)
print(s)
Python's favorite
food is perl

"Python is very easy." he says.
Python's favorite food is perl
"Python is very easy."
 he says.

 

문자열 더하기(+) : 연결

a = "happy"
b = "birthday"
print(a+b)
happybirthday

 

문자열 곱하기(*) : 반복

a = "happy"
print(a*2)
happyhappy

 

문자열 길이 구하기 : len()

a = "happy"
print(len(a))
5

 

문자열 인덱싱

#    0123456789012345678901234567890123
a = "Life is too short, You need Python"
#뒤에서                         87654321
print(a[0])
print(a[12])
print(a[-1])    #뒤에서 첫번째
print(a[-2])
print(a[-5])

문자열 앞부터 인덱싱 (0, 1, 2, ...)

문자열 뒤부터 인덱싱 (-1, -2, -3, ...)

L
s
n
o
y

 

문자열 슬라이싱 변수이름[시작번호:끝번호]

#    0123456789012345678901234567890123
a = "Life is too short, You need Python"
#    4321098765432109876543210987654321
print(a[0:4])   #0부터 3까지 (4는 포함되지 않는다)
print(a[19:-7]) #19 ~ -8까지
Life
You need

자바의 subString과 유사한 기능

  • 변수이름[시작번호:끝번호] : 시작번호 ~ 끝번호-1까지 슬라이싱 (마지막 번호는 포함되지 않는다.)
  • 시작번호를 생략할 경우 : 처음부터~끝번호-1
  • 끝번호를 생략할 경우 : 시작번호부터 끝까지 출력
#    0123456789012345678901234567890123
a = "20210329Rainy"
b = a[:8]
c = a[8:]
d = a[:]

print(b)
print(c)
print(d)
20210329
Rainy
20210329Rainy

 

문자열 바꾸기 

예) Pithon 이라는 문자열을 Python 으로 바꾸기 

문자열 요소는 바꿀 수 없다.

#    012345
a = "Pithon"
#a[1]=y => error
p = a[0] + "y" + a[2:]
print(p)

새로운 변수를 만들어 슬라이싱을 활용하여 문자열을 새로 만들어 주었다.

파이썬에서 문자열 자료형은 변경이 불가능한 자료형이므로, a[1] = y 에서 오류가 발생하기 때문이다.

 

혹은, replace(기존 문자열, 바꿀 문자열) 를 이용해서 문자열을 바꿀 수 있다.

replace를 사용했을 때, a안에 i가 여러개라면 해당 i가 모두 y로 변하게 돼어 주의해야한다.

a = "Pithon"
a = a.replace('i','y')
print(a)

 

문자열 포맷 코드

코드 설명
%s 문자열 (String)
%c 문자 1개 (Character)
%d 정수 (Integer)
%f 부동소수 (Floating-point)
%o 8진수
%x 16진수
%% 문자 % 자체

🔍 [Python] 문자열 포맷 코드, 포맷팅 예시

 


점프 투 파이썬 : wikidocs.net/13

728x90

'Python' 카테고리의 다른 글

[Python] 문자열 포맷 코드, 포맷팅 예시  (0) 2021.04.07
[Python] 스택 / 큐  (0) 2021.04.06
[Python] 숫자 연산자  (0) 2021.03.29
파이참 단축키 정리  (0) 2021.03.29
파이참 폰트 크기 변경  (0) 2021.03.29