STRINGS - 문자열

  • 각각의 하나의 문자들이 나열된 상태, 즉 시퀀스(sequence) 이다!!!
  • 문자열은, 싱글퀏이나 더블퀏 (single or double quotes)으로 감싸야 한다.
x = 'Hello World'
y = "Hello World"
k = '''hello
world'''

 

문자열을 다루는 함수들

+ 연산자는, 숫자 뿐만 아니라 문자열에서도 사용이 가능하다.

first_name = 'Mitch'
last_name = 'Steve'
full_name = first_name + " " + last_name

# Mitch Steve
print(full_name)

대소문자로 바꿀수 있다.

# MITCH STEVE
print(full_name.upper())

# mitch steve
print(full_name.lower())

# Mitch Steve
print(full_name.title())

문자열을 원하는기준으로, 각각 분리해 낸다.

# ['mitch', 'steve']
print(full_name.split())

# ['mi', 'ch s', 'eve']
print(full_name.split('t'))

문자열의 일부를 추출하기 Slicing 슬라이싱

  • [:] 처음부터 끝까지
  • [start:] start오프셋부터 끝까지
  • [:end] 처음부터 end-1 오프셋까지
  • [start : end] start오프셋부터 end-1 오프셋까지
  • [start : end : step] step만큼 문자를 건너뛰면서, 위와 동일하게 추출
letters = 'abcdefghijklmnopqrstuvwxyz'

# cdefg
letters[2:6 +1]

# abcdef
letters[:6]

# fghijklmnopqrstuvwxyz
letters[5:]

# xyz
letters[-3:]

# acegikmoqsuwy
letters[::2]

문자열의 길이

  • len() 함수를 사용하여 몇개의 문자로 되어있는지 알 수 있다.
#26
len(letters)

문자열 위치 찾기

  • find 함수는, 찾고자 하는 문자열이 존재하는 곳의 첫번째 오프셋을 알려준다.
  • rfind 함수는, 찾고자 하는 문자열이 있는 마지막 오프셋을 알려준다.
  • count() 함수는 몇개의 문자열이 있는지 알려준다.

 

 

poem = '''So "it is" quite different, then, if in a mountain town
the mountains are close, rather than far. Here

they are far, their distance away established,
consistent year to year, like a parent’s

or sibling’s. They have their own music.
So I confess I do not know what it’s like,

listening to mountains up close, like a lover,
the silence of them known, not guessed at.'''

# 162
print(poem.find('year'))

# 170
print(poem.rfind('year'))

# 0
print(poem.find('So'))

# 2
poem.count('year')

'파이썬' 카테고리의 다른 글

Booleans - True and False  (0) 2022.04.20
파이썬 Dictionaries - get, keys, values,items 함수  (0) 2022.04.20
파이썬 List(배열)  (0) 2022.04.19
Print Operation and Get User input  (0) 2022.04.18
파이썬 변수, 숫자, 연산  (0) 2022.04.18

+ Recent posts