반응형

Day5가 어제엿는데 토요일이라서 수행해야할 섹션이 2개였다. 
그래서 오늘도 주말이어서 2개일줄 알고 메일을 클릭했는데 오늘수행해야할 섹션은 1개다!
개인적으로 다른공부도 많이 하고있어서 양이 조금 걱정됐는데 다행이다!
오늘 Day6도 기분좋게 수행하자!

Today's Assignment - day 6

오늘은 Strings 와 Dictionaries에 관한 내용이다!

Strings

이섹션에서는 파이썬의 기본 제공 문자열 메소드와 포맷 작업에 대해 설명한다.
이러한 무자열 조작패턴은 데이터 사이언스 작업의 맥락에서 자주 나타난다.

String syntax

이전 과정에서는 많은 문자열을 예제로 살펴 보았지만, 파이썬의 문자열은 따옴표또는 쌍따옴표를 사용하여 정의할 수 있다. 기능은 동일하다.

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

작은 따옴표를 문자열로 사용하고 싶으면, 큰따옴표로 문자열을 감싸주면 된다.
반대의 경우에도 마찬가지이다.

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

만약, 작은 따옴표가 있는 문자열에 작은 따옴표로 감싸려고 하면, 파이썬이 혼란스러워한다. 즉, 에러가 발생한다.

'Pluto's a planet!'

역슬래시를 따옴표나 큰따옴표 앞에 붙혀주면 문자그대로 인식하게 한다.

'Pluto\'s a planet!'

아래 표에는 역슬래시의 몇가지 중요한 용도가 적혀 있다.

마지막에 있는 \n 은 줄바꿈을 의미한다.

hello = "hello\nworld"
print(hello)

그리고, 따옴표나 쌍따옴표를 연속으로 3개 사용하면 문자그대로 새로운 줄을 포함할 수 있다. (즉 \n을 사용하지 않고, 문자그대로 엔터만 누르면 된다) 문자열을 정의하는 곳이라면 어디서나 사용할 수 있다.

triplequoted_hello = """hello
world"""
print(triplequoted_hello)
triplequoted_hello == hello

기본값 '\n"이 아닌 키워드 인수의 끝 값을 지정하지 않으면 print()함수는 자동으로 새 줄 문자를 추가한다.

print("hello")
print("world")
print("hello", end='')
print("pluto", end='')



Strings are sequences

문자열은 문자의 시퀀스로 생각할 수 있다. 리스트에서 사용했던 거의 모든 것들을 문자열에도 적용할 수 있다.

# Indexing
planet = 'Pluto'
planet[0]

# Slicing
planet[-3:]

# How long is this string?
len(planet)

# Yes, we can even loop over them
[char+'! ' for char in planet]

그러나 중요하게 다른점은, 수정할 수 없다는 것이다.(불변)

planet[0] = 'B'
# planet.append doesn't work either

 

String methods

리스트처럼 str유형에는 매우 유용한 메서드가 많이 있다. 

# ALL CAPS
claim = "Pluto is a planet!"
claim.upper()

# all lowercase
claim.lower()

# Searching for the first index of a substring
claim.index('plan')

claim.startswith(planet)



Going between strings and lists: .split() and .join()

str.split()은 문자열을 더 작은 문자열 리스트로 변환하며 기본적으로는 공백으로 구분하여 자른다.
이것은 하나의 큰 문자열에서 단어 목록으로 이동시키는 데 매우 유용하다.

words = claim.split()
words

때로는 공백이 아닌 다른 것으로 나누기를 할 수도 있다.

datestr = '1956-01-31'
year, month, day = datestr.split('-')

str.join()은 문자열 리스트의 요솟값들 사이에 원하는 문자를 구분기호로 사용하여 하나의 긴 문자열로 만들어 준다.

'/'.join([month, day, year])

 

# Yes, we can put unicode characters right in our string literals :)
' 👏 '.join([word.upper() for word in words])

Building strings with .format()

파이썬은 사용하면 문자열을 +연산자를 이용하여 연결할 수 있다.

planet + ', we miss you.'

만약 str형태가 아닌 객체를 합치고 싶으면, str()을 먼저 호출해야한다.

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

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

position의 9가 str형태로 정상적으로 들어갔다.

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

이것은 읽기가 어렵고, str.format()을 입력하기 어렵다.
그래서 우리는 훨씬 깔끔할 것을 이용할 것이다.
문자열 포맷코드를 이용할 것이다.
.format의 형식을 이용하면 정말 간단하다.



pluto_mass = 1.303 * 10**22
earth_mass = 5.9722 * 10**24
population = 52910390
#         2 decimal points   3 decimal points, format as percent     separate with commas
"{} weighs about {:.2} kilograms ({:.3%} of Earth's mass). It is home to {:,} Plutonians.".format(
    planet, pluto_mass, pluto_mass / earth_mass, population,
)

# Referring to format() arguments by index, starting from 0
s = """Pluto's a {0}.
No, it's a {1}.
{0}!
{1}!""".format('planet', 'dwarf planet')
print(s)



Dictionaries

딕셔너리는 Key와 Value로 이루어져있다. 서로 매핑되어있다.

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

이 경우 'one', 'two', 'three' 가 key이고 value는 1, 2, 3 이다.

Value는 리스트나 문자열에 인덱싱하는 것과 유사하게 대괄호 구문을 통해 액세스 된다.

numbers['one']

key, value 쌍을 추가할 수 있다.

numbers['eleven'] = 11
numbers

또는 기존  key와 관련된 value를 변경하려면,  아래와 같이 하면된다.

numbers['one'] = 'Pluto'
numbers

파이썬은 이전 섹션에서 봤던 리스트 이해와 유사 기능을 가지고 있다. 

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

operator가 딕셔너리 key인지 여부를 알려준다.

'Saturn' in planet_to_initial

'Betelgeuse' in planet_to_initial

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

dict.key() 및 dict.values()를 각각 사용하여 모든 key또는 모든 value에 액세스 할 수 있다.

# Get all the initials, sort them alphabetically, and put them in a space-separated string.
' '.join(sorted(planet_to_initial.values()))


매우 유용한 dict.items() 메서드를 사용하면 사전의 키와 값을 동시에 반복할 수 있다.(Python 전문 용어에서 항목은 key, vlaue 쌍을 나타낸다.)

for planet, initial in planet_to_initial.items():
    print("{} begins with \"{}\"".format(planet.rjust(10), initial))


딕셔너리의 추가적인 내용을 알아보려면 아래 링크를 참고하도록 하자!
official online documentation

 

Built-in Types — Python 3.9.6 documentation

The following sections describe the standard types that are built into the interpreter. The principal built-in types are numerics, sequences, mappings, classes, instances and exceptions. Some collection classes are mutable. The methods that add, subtract,

docs.python.org

exercise를 정리한 코드를 공유한다!
https://github.com/mgkim-developer/30-Days-of-ML-with-Kaggle/blob/main/30-days-of-ml-day-6.ipynb

 

GitHub - mgkim-developer/30-Days-of-ML-with-Kaggle: 30 Days of ML with Kaggle

30 Days of ML with Kaggle. Contribute to mgkim-developer/30-Days-of-ML-with-Kaggle development by creating an account on GitHub.

github.com

 

반응형