오늘도 한 뼘 더

[Python] 파이썬 기초, 자료형 - 문자열 자료형 본문

Study/Python

[Python] 파이썬 기초, 자료형 - 문자열 자료형

나른한댕댕이🐶 2022. 9. 14. 22:55
728x90
반응형

# 문자열

  • 문자, 단어 등으로 구성된 문자들의 집합을 의미한다.

 

## 문자열 만드는 방법

 

1. 큰 따옴표(") 사용

 "Hello Jihyunb"

 

2. 작은따옴표(') 사용

 'Hello World'

 

3. 큰 따옴표 3개 연속(""") 사용

 """You Only Live Once"""

 

4. 작은따옴표 3개 연속(''') 사용

 '''Enjoy your Life'''

 

## 중간에 작은따옴표(') / 큰 따옴표(") 넣기

 "Python says 'Hi'"
 
 '"Python" is good language'
 
 'Python\'s favorite food'

 

## 여러 줄인 문자열 대입하기

 

1. \n 사용하기

 >>> multiline = "Hello World \nLife is beautiful"
 
 >>> print(multiline)
 Hello World
 Life is beautiful

 

2. 연속된 작은따옴표(''') 3개 또는 큰 따옴표(""") 3개 사용하기

 >>> multiline = """
  Hello World
  Life is beautiful
  """

 

# 문자열 연산

 

## 더하기

 >>> head = "Hello"
 >>> tail = "World"
 >>> head + tail
 "Hello World"

 

## 곱하기

 >>> a = 'python'
 >>> a * 3
 'pythonpythonpython'

 

## 문자열 길이 구하기

 >>> a = "Life is beautiful"
 >>> len(a)
 
 17

 

# 문자열 인덱싱 & 슬라이싱

  • 인덱싱 : 특정 위치의 문자를 뽑아낸다
 >>> a = "Hello World Life is beautiful"
 >>> a[0]
 "H"
 
 >>> a[4]
 "o"
 
 >>> a[-1]
 "l"

 

  • 슬라이싱 : 문자열을 뽑아낼 때 쓰는 방법
  >>> a = "Hello World Life is beautiful"
  >>> a[0:4]
  "Hell"
  
  >>> a[-2:]
  "ul"

 

# 문자열 포매팅

1. 숫자 바로 대입

 >>> d = "There is %d apples" %2
 There is 2 apples

 

2. 문자열 바로 대입

 >>> d = "There is %s apples" % "two"
 There is two apples

 

3. 변수 대입

 >>> number = 2
 >>> d = "There is %d apples" % number
 There is 2 apples

 

4. 2개 이상 값 대입

 >>> d = "There id %d apples and %s peaches" % (3, "five")
 There id 3 apples and five peaches

 >>> number = 3
 >>> word = "five"
 >>> d = "There id %d apples and %s peaches" % (number, word)
 There id 3 apples and five peaches
728x90
반응형

'Study > Python' 카테고리의 다른 글

[Python] 파이썬 기초, 자료형 - 숫자형  (0) 2022.09.14
Comments