Program/[Kaggle] 30 Days of ML
[30 Days of ML] Day 6
uding9
2021. 8. 11. 01:17
반응형
Tutorial
Strings
String syntax
아래와 같은 경우 에러 발생
'Pluto's a planet!'
File "<ipython-input-3-a43631749f52>", line 1
'Pluto's a planet!'
^
SyntaxError: invalid syntax
백슬래쉬(\)을 통해 고칠 수 있음
'Pluto\'s a planet!'
"Pluto's a planet!"
Strings are sequences
strings은 일련의 characters로 생각할 수 있음
strings는 시퀀스임
문자열은 리스트와 유사하게 인덱싱, 슬라이싱으로 접근할 수 있음(그 외에도 len
, max
, min
함수 등을 적용할 수 있음)
planet = 'Pluto'
print(planet[0])
P
리스트와 다른 점은 수정할 수 없다는 것임
planet[0] = 'B'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-6-1d457fe13bd8> in <module>
----> 1 planet[0]='B'
TypeError: 'str' object does not support item assignment
String methods
claim = "Pluto is a planet!"
print(claim.index('plan')) # 입력받은 문자열의 첫 번째 인덱스 번호 반환
print(claim.startswith(planet)) # 'Pluto'로 시작하는가?
print(claim.endswith('dwarf planet')) # 'dwarf planet'으로 끝나는가?
11
True
False
Going between strings and lists: .split()
and .join()
str.split()
쪼개기 str.join()
붙이기
Building strings with .format()
str.format()
을 사용하면 깔끔함
planet='Pluto'
position=9
"{}, you'll always be the {}th planet to me.".format(planet, position)
"Pluto, you'll always be the 9th planet to me."
format()
은 다양하게 활용됨
pluto_mass = 1.303 * 10**22earth_mass = 5.9722 * 10**24population = 52910390"{} weighs about {:.2} kilograms ({:.3%} of Earth's mass). It is home to {:,} Plutonians.".format( planet, pluto_mass, pluto_mass/earth_mass, population)
"Pluto weighs about 1.3e+22 kilograms (0.218% of Earth's mass). It is home to 52,910,390 Plutonians."
s = """Pluto's a {0}.No, it's a {1}.{0}!{1}!""".format('planet', 'dwarf planet')print(s)
Pluto's a planet.No, it's a dwarf planet.planet!dwarf planet!
Dictionaries
딕셔너리는 key와 value를 매핑하는 Python 내장 데이터 구조임
in
연산자는 사전에 키가 있는지 여부를 알려줌
planet_to_initial={'Mercury': 'M', 'Venus': 'V', 'Earth': 'E', 'Mars': 'M', 'Jupiter': 'J', 'Saturn': 'S', 'Uranus': 'U', 'Neptune': 'N'}print('Saturn' in planet_to_initial)print('Betelgeuse' in planet_to_initial)
TrueFalse
dict.keys()
와 dict.values()
를 통해 딕셔너리의 key와 value에 접근할 수 있음
dict.items()
사용하면 딕셔너리의 key-value 쌍을 동시에 반복할 수 있음
Exercise
1.
내 코드
def is_valid_zip(zip_code): """Returns whether the input string is a valid (5 digit) zip code """ return False if len(zip_code)<5 else zip_code.isdigit()
답 코드
def is_valid_zip(zip_str): return len(zip_str) == 5 and zip_str.isdigit()
연산자보다 조건문에 익숙한 나..
반응형