본문 바로가기

Python_Beginer/Study

Python String(문자열)

반응형

1. 문자열

문장을 표현하는 글자 모임의 변수


2. 표현방식

2-1. 쌍따옴표

str1 = "Life is too short"

2-2. 홀따옴표

str2 = 'You need Python'

2-3. 쌍따옴표 / 홀따옴표 혼용 사용 안됨(단독 사용)

2-3-1. 에러 발생 코드 예제

str1 = "Life is too short'
print(str1)

2-3-2. 에러 발생 코드 실행 결과

File "C:/python/string._error.py", line 1

    str1 = "Life is too short'

                             ^

SyntaxError: EOL while scanning string literal


Process finished with exit code 1


3. 문자열 연산자

3-1. + (덧셈)

문장과 문장을 연결하는 연산자.


3-1-1. 예제 Code


3-1-1-1. 문자열 + 문자열은 가능하다.

str1 = "Life is too short"
str2 = 'You need Python'
print(str1 + str2)

3-1-1-1. 출력물

Life is too shortYou need Python


3-1-1-2. 문자열 + 숫자은 할수 없다.(타입 에러)

str1 = "Life is too short"
print(str1 + 100)

3-1-1-2. 출력물

Traceback (most recent call last):

  File "C:/python/string._error.py", line 3, in <module>

    print(str1 + 100)

TypeError: can only concatenate str (not "int") to str


Process finished with exit code 1


3-2. *(곱셈)

문자열을 곱한만큼 반복하는 연산자.


3-2-1. 예제 Code


3-2-1. 문자열 * 숫자

str1 = "Life is too short"
print(str1 * 3)

3-2-1. 출력물

Life is too shortLife is too shortLife is too short


4. 이스케이프 문자

파이썬 특수문자 / 역슬래시를 사용하여 표현

4-1. 많이 사용되는 종류

4-1-1. \n : 줄바꿈

str1 = 'python\npython'
print(str1)

4-1-1. 결과물

python

python


Process finished with exit code 0

4-1-2. \\\ : \(역슬래시 경로 표현에 사용)

str1 = 'c:\\python'
print(str1)
4-1-2. 결과물
c:\python

Process finished with exit code 0

4-1-3. \' : 문자열 안에 '(홀따움표)을 표현

str1 = 'I\'m happy to see you'
print(str1)

4-1-3. 결과물

I'm happy to see you


Process finished with exit code 0


4-1-4. \" : 문자열 안에 "(쌍따옴표)를 표현

str1 = 'I\'m happy to see you. \"Ki\"'
print(str1)

4-1-4. 결과물

I'm happy to see you. "Ki"


Process finished with exit code 0


5. 인덱스

각 각 글자에 부여되는 번호(0번부터 시작/ -1번부터 시작)

5-1. 앞에서 인덱싱

0

1

2

3

4

5

6

7

8

9

10

11

h

e

l

l

o

 

p

y

t

h

o

n


5-2. 뒤에서 인덱싱

-12

-11

-10

-9

-8

-7

-6

-5

-4

-3

-2

-1

h

e

l

l

o

 

p

y

t

h

o

n


5-3. 기본 표현법

변수[시작위치:끝위치]


5-4. 예제 Code>

str = 'Life is too short, You need Python'

# 3번째 문자 추출 -> 0부터 카운트
print(str[3])

# 뒤에서 3번째 글자 추출 -> -1부터 카운트
# 0과 -0이 같은 값이기 때문
print(str[-3])

# 앞에서 0번째 부터 3번째 전 까지의 문자 추출
print(str[0:3])

# 앞에서 5번째 부터 7번째 전 까지의 문자 추출
print(str[5:7])

# 앞에서 19번째 부터 끝까지 추출
print(str[19:])

# 처음부터 앞에서 17번째 전 까지의 문자 추출
print(str[:17])

# 처음부터 끝까지 추출
print(str[:])

# 앞에서 19번째부터 뒤에서 -7번째 다음까지 추출
print(str[19:-7])

5-4. 츨력물

e

h

Lif

is

You need Python

Life is too short

Life is too short, You need Python

You need


Process finished with exit code 0


6. 포맷팅

형식 문자에 특정 변수 값을 적용하여 완성된 문자열을 만드는 법

6-1. 형식 문자

형식 문자

설명

%d

정수(10진수)

%f

실수(10진수)

%s

문자열

%c

문자1개

%o

8진 정수

%x

16진 정수


6-2. 예제 코드

# %d 정수
str1 = '제육덮밥은 %d원입니다.' % 5000
print(str1)

# %f 실수
str2 = '파이는 %f이다.' % 3.14
print(str2)

# %s 문자열
str3 = '%s 검색어를 입력하세요.' % '신병'
print(str3)

6-2. 출력물

제육덮밥은 5000원입니다.

파이는 3.140000이다.

신병 검색어를 입력하세요.


Process finished with exit code 0


반응형