본문 바로가기
파이썬(Python)

(6) 파이썬(Python)이란? - Strings and Dictionaries [Hellfer]

by Hellfer 2024. 7. 14.
728x90

https://www.kaggle.com/code/colinmorris/strings-and-dictionaries

 

Strings and Dictionaries

Explore and run machine learning code with Kaggle Notebooks | Using data from No attached data sources

www.kaggle.com

 

위의 글을 참고하여 작성하였습니다.

 

문자열은 작은따옴표(')나 큰따옴표(")를 사용하여 정의할 수 있습니다.

 

x = 'Pluto is a planet'
y = 'pluto is a planet'
x == y

 

True

 

마찬가지로, 작은따옴표로 묶으면 큰따옴표가 포함된 문자열을 쉽게 만들 수 있습니다.

 

print("Pluto's a planet!")
print('My dog is named "Pluto"')

 

Pluto's a planet!

My dog is named "Pluto"

 

작은따옴표로 묶인  문자열 안에 작은따옴표를 또 넣으려고 하면 오류가 발생합니다.

 

'Pluto's a planet'

 

SyntaxError : invaild syntax

 

해결하는 방법은 다음과 같습니다.

 

이스케이프 문자(\)를 사용하여 작은따옴표를 처리할 수 있습니다.

 

'Pluto\'s a planet!'

 

Pluto's a planet

 

입력 출력 예시 print(예시)
\' ' 'What\ 's up? What's up?
\" " "That's \"Cool\"" That's "cool"
\\ \ "Look, a mountain: /\\" Look, a mountain: /\
\n   "1\n2 3" 1
23

 

'\n'은 줄 넘김으로 새 줄을 시작하게 해 줍니다.

 

hello = "hello\nworld"

print(hello)

 

 

hello

world

 

삼중따옴표(''' 또는 """)를 사용하면 문자열 내에 개행 문자를 포함할 수 있습니다.

 

triplequoted_hello = """hello world"""

print(triplequoted_hello)

 

hello world

 

print() 함수는 따로 '\n'을 사용할 필요 없이 자동으로 줄 넘김이 되게 해 줍니다.

 

print("hello")
print("world")
# end=''로 설정하면 줄바꿈 없이 출력으로 이어짐
print("hello", end='')
print("world", end='')

 

 

hello

world

helloworld

 


 

문자열은 문자들의 시퀀스로. 리스트와 유사하게 다양한 작업을 수행할 수 있습니다.

 

# 인덱싱
planet = 'Pluto'
planet[0]

 

'P'

 

# 슬라이싱
planet[-3:]

 

'uto'

 

# 문자길이
len(planet)

 

5

 

# 조건문 삽입
[char+'!' for char in planet]

 

['P!', 'l!', 'u!', 't!', 'o!']

 


 

 

리스트와 가장 큰 차이점은 문자열은 변경이 불가능하여 수정할 수 없습니다.

 

planet[0] = 'B'

 

TypeError : 'str' object does not support item assignment

 

문자열 유형도 다양한 메서드를 제공합니다.

 

# 대문자로 변환
claim = "Pluto is a planet!"
claim.upper()

 

PLUTO IS A PLANET

 

# 소문자 변환
claim.lower()

 

pluto is a planet

 

# 특정 접두사로 시작하는지
claim.startswith(planet)

 

True

 

# 문자열이 특정 접미사로 끝나는지
claim.endswith('planet')

 

False

 

# 문자열을 특정 기준으로 나누어 리스트로 반환
words = claim.split()
words

 

['Pluto', 'is', 'a', 'planet!']

 

date = '2024-07-14'
year, month, day = date.split('-')
# year = 2024, month = 07, day = 14

 

# 특정 문자열을 하나로 합침
'/'.join([year, month, day])

 

'2024/07/14'

 

'👏'.join([word.upper() for word in words])

 

'PLUTO 👏 IS 👏 A 👏 PLANET!'

 


 

. format()으로 문자열 만들기, + 연산자를 사용하여 문자열을 연결할 수 있습니다.

 

planet + ', we miss you.'

 

'planet, we miss you.'

 

str() 함수를 사용하여 비문자열 객체를 문자열로 변환하면, 타입 에러 없이 문자열 결합이 가능합니다.

 

position = 9
planet + ", you'll always be the " + position + "th planet to me."

 

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

 

planet + ", you'll always be the " + str(position) + "th planet to me."

 

"Pluto, you'll always be the 9th planet to me."

 


 

아래는 몇 가지 문자열 format 방법입니다.

 

"{}, you'll always bo the {}th planet to me.".format(planet, position)


"Pluto, you'll always be the 9th planet to me."

 

f"{planet}, you'll always be the {position}th planet to me."

 

"Pluto, you'll always be the 9th planet to me."

 

"%s, you'll always be the %dth planet to me." %(plnaet, position)

 

"Pluto, you'll always be the 9th planet to me."

 


 

딕셔너리는 키(Key)와 값(Value)을 쌍으로 저장하는 데이터 구조입니다.

 

numbers = {'one' : 1, 'two' : 2, 'three' : 3}

 

'one', 'two', 'three'는 키(Key)이고 1,2,3은 값(Value)입니다.

 

numbers['one']

 

1

 

다른 키(Key)와 값(Value) 쌍을 추가할 수 있습니다.

 

numbers['eleven'] = 11

 

{'one': 1, 'two': 2, 'three': 3, 'eleven': 11}

 

또한 키(Key)와 값(Value)을 수정할 수 있습니다.

 

numbers['one'] = 5
numbers

 

{'one': 5, 'two': 2, 'three': 3, 'eleven': 11}

 

planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
planet_to_initial = {planet: planet[0] for planet in planets}
planet_to_initial

 

{'Mercury': 'M',
 'Venus': 'V',
 'Earth': 'E',
 'Mars': 'M',
 'Jupiter': 'J',
 'Saturn': 'S',
 'Uranus': 'U',
 'Neptune': 'N'}

 

'in' 연산자는 딕셔너리 안에 키(Key)가 있는지 여부를 알려줍니다.

 

'Saturn' in planet_to_initial

 

True

 

'Betelgeuse' in planet_to_initial

 

False

 

for i in numbers:
    print("{} = {}".format(i, numbers[i])

 

one = 5

two = 2

three = 3

eleven = 11

 


 

딕셔너리의 Keys(), values(), item() 메서드는 키, 값, 키-값 쌍을 정렬하거나 동시에 순회하는 작업을 보여줍니다.

 

딕셔너리의 값 정렬 및 문자열 결합

# 예시 딕셔너리
planet_to_initial = {
    'Mercury': 'M', 
    'Venus': 'V', 
    'Earth': 'E', 
    'Mars': 'M', 
    'Jupiter': 'J', 
    'Saturn': 'S', 
    'Uranus': 'U', 
    'Neptune': 'N'
}

# 모든 값들을 정렬하고, 공백으로 구분된 문자열로 결합
sorted_initials = ' '.join(sorted(planet_to_initial.values()))
print(sorted_initials)  # 'E J M M N S U V'

 

 

딕셔너리의 키와 값을 동시에 순회

 

# 키와 값을 동시에 순회하며 출력
for planet, initial in planet_to_initial.items():
    print("{} begins with \"{}\"".format(planet.rjust(10), initial))

# 출력 결과:
#   Mercury begins with "M"
#      Venus begins with "V"
#      Earth begins with "E"
#       Mars begins with "M"
#    Jupiter begins with "J"
#     Saturn begins with "S"
#     Uranus begins with "U"
#    Neptune begins with "N"

 

 

여기서 planet.rjust(10)은 문자열을 오른쪽으로 정렬하여 10칸의 공간을 확보합니다.

 

다른 유용한 딕셔너리 메서드들도 있습니다.

 

dict.get(key, default) : 키가 존재하지 않을 경우 기본값을 반환합니다.

dict.update(other_dict) : 다른 딕셔너리의 키-값을 추가하거나 갱신합니다.

dict.pop(key, default) : 키가 존재하면 값을 반환하고 키-값 쌍을 딕셔너리에서 제거합니다.

 

# 예시
print(planet_to_initial.get('Pluto', 'N/A'))  # 'N/A'

# 다른 딕셔너리 병합
additional_planets = {'Pluto': 'P'}
planet_to_initial.update(additional_planets)
print(planet_to_initial)  # {'Mercury': 'M', 'Venus': 'V', 'Earth': 'E', 'Mars': 'M', 'Jupiter': 'J', 'Saturn': 'S', 'Uranus': 'U', 'Neptune': 'N', 'Pluto': 'P'}

# 키와 값을 제거하며 반환
print(planet_to_initial.pop('Pluto', 'N/A'))  # 'P'
print(planet_to_initial)  # {'Mercury': 'M', 'Venus': 'V', 'Earth': 'E', 'Mars': 'M', 'Jupiter': 'J', 'Saturn': 'S', 'Uranus': 'U', 'Neptune': 'N'}

 

728x90