Service/Coding

Google Python Automation Certification - Week 4

포항돼지 2022. 2. 3. 17:52

Data Type

String, List, Dictionary

 

1. What is String?

Data Type in Python.

 = Empty String

 = Using + sign is Concatenating(사슬같이 잇다, 연결시키다)

 = len(pet) = number of character

 

So it is very important to know how to use them.

 

def double_word(word):
    return word *2 + str(len(word)*2)   #return 에다가 print 안쓰고 그냥 word string에 연산 가능. len function은 str 로 감싸줘야 functioning 함

print(double_word("hello")) # Should return hellohello10
print(double_word("abc"))   # Should return abcabc6
print(double_word(""))      # Should return 0

String을 잘 쓰려면, String에 어떤 옵션 들이 있는지 잘 알아야됨, 지금부터 그 옵션을 한번 보자

 

String Indexing

리스트 Indexing이랑 비슷한거인듯, 0부터 시작
Index 6 print하려면 에러나옴

Negative Indexing = String 뒤에서부터 인덱스 프린트 하는거

정확한 index 값 몰라도 뒤에서부터 이렇게 출력 가능

def first_and_last(message):
    if not message or message[0] == message[-1]:
        return True
    else:
        return False
print(first_and_last("else"))
print(first_and_last("tree"))
print(first_and_last(""))
 
이게 왜 not 이랑 or이 들어가는지 설명을 해줘야지 씨발 좆 같은 그냥 던져놓고 시발 알아서 해라식이네
아, 확인 해보니까 if message만 쓰면, 그냥 그 스트링 자체 확인 가능하네.
이런식으로 string 들어있는거는 True로 나오고, 안 들어 있는거는 False로 나옴

그래서 if not message 거나 message 스트링 비교 했을때 조건이 맞다면 True, 주고 empty인거 보면 False주는 게 

if not message or message[0] == message[-1]로 되는거네, 시발

 

좆 같은 2분짜리 강의로 이해하려고 15분째 코딩하고 있네 시발 병신 고한길

Slice == substring
Index 1 to 3 까지 print
access from nothing to 4, 4 to nothing (end)
스트링은 이렇게 Indexing으로 value바꾸는게 불가능하다, immutable해서(Tuple이랑 같은 성질) 근데 list는 바꾸는거 가능함
이렇게 New value assign해서 고치는거 가능, 그래서 overwrite 해서 고치면됨
이렇게 코드 두줄 더 쓰고 벨류 값 바꾸기 가능
Method function, index 값 확인 하는 기능
substring에 2개 값이 있는경우, 제일 앞쪽꺼만 print out 해줌

꼭 Bracket으로 써야함, value.index("Pet") 이런식으로

in 써서, Specific String이 True인지 False인지 Boolean Type으로 확인 가능

 

자! 이제 예를 들어보자,

만약 회사 URL이 바뀌어서 old email -> new email로 바꾸고 싶다? == String modification이 필요한 상황임

 def replace_domain(email, old_domain, new_domain): #3개의 parameter를 가진 function을 만들자 

   if "@" + old_domain in email: # 만약 @dymos.com 이 email 안에 있는지 확인을 하고 만약 있으면

 

       index = email.index("@" + old_domain)  #옛날 도메인 index 시작 번호를 가꼬와서 email.index("") == index 넘버 체크하는 function 새로운 index value에다가 넣고

 

       new_email = email[:index] + "@" + new_domain #새로운 new_email 벨류에다가 아까만든 index 번호 앞꺼, 즉 email ID만 가져온다음 + "@" + new_domain 값넣어주고

 

       return new_email #해줘서 old email -> new email로 바뀌는 fuction 완성

   return email #, 만약 없으면 그냥 email return

 

Capital & Minimal Method
이렇게 YeS 나 뭐 아무렇게 입력 받아도 이 .lower() medoth 쓰면 판별 가능

 

Strip == Srounding space 없애는거 , Tab, inline charactor

strip은 그냥 space없애는 거고, lstrip은 왼쪽 으로 strip없애기 rstrip은 오른쪽으로 스트립 없애기, 즉 중간 기준, rstrip쓰면 오른쪽 strip이 날아감
.count("e") = 몇번 String 들어갔는지
.endswith("value")는 String의 마지막이 이 String인지 Boolean으로 확인
스트링이 숫자인지 확인
.join() , 중간에 넣는 거
y = "Wayne is Byunshin"
x = " ".join(y)
print(x)
 

이렇게 String이 있는경우는, string.index 마다 스페이스 넣기 뭐 이런식으로 가능
.split 써서 리스트에 넣어줌

 

잘 이해는 안되지만, split해서 스페이스를 기준으로 리스트에 넣은다음, words를 for문으로 돌리는데,  word[0] == 리스트 값의 처음 letter를 .upper() function으로하면 리스트가 있는대로 돌아감. 근데 result 값이 왜 = ""야 하는지 모르겠음. 아! empty 여야, 그 안에다가 담을수 있으니까 그런것인듯

 

 

like "this is a string".upper(). This would return the string "THIS IS A STRING" 

이렇게 스트링 뒤에 사용 가능 하니까 word[0].upper() 붙여서 쓴거구나 ..

 

format Method

curly bracket 넣어서 , .format medoth 뒤에 value넣은 다음 입력 가능. curly bracket은 무조건 empty임

 

한줄로 format method 끝내려면, 저렇게 curly bracket안에 value 넣고 .format 뒤에 value를 직접 입력 해줘야함

def student_grade(name, grade):
    return "{} received {}% on the exam".format(name,grade)
    
print(student_grade("Reed"80))
print(student_grade("Paige"92))
print(student_grade("Jesse"85))

return 에 print function 쓰면 에러남.. 

Formatting expression

: == 필드네임

.2f == float 넘버로, 2 digit으로 표시하겠다

 

전에 했던 celsius function

>3 == 3개의 space를 가지겠다

>6 == 6개의 space를 가지겠다

 

아~ 스트링 뒤에 더 옵션을 붙이기위해서 : 라는 기준점을 잡은거구나! 즉 {}이거랑 같은 표식이네 !!

 

 

String Cheet Sheet

String operations

  • len(string) Returns the length of the string
  • for character in string Iterates over each character in the string
  • if substring in string Checks whether the substring is part of the string
  • string[i] Accesses the character at index i of the string, starting at zero
  • string[i:j] Accesses the substring starting at index i, ending at index j-1. If i is omitted, it's 0 by default. If j is omitted, it's len(string) by default.

String methods

  • string.lower() / string.upper() Returns a copy of the string with all lower / upper case characters
  • string.lstrip() / string.rstrip() / string.strip() Returns a copy of the string without left / right / left or right whitespace
  • string.count(substring) Returns the number of times substring is present in the string
  • string.isnumeric() Returns True if there are only numeric characters in the string. If not, returns False.
  • string.isalpha() Returns True if there are only alphabetic characters in the string. If not, returns False.
  • string.split() / string.split(delimiter) Returns a list of substrings that were separated by whitespace / delimiter
  • string.replace(old, new) Returns a new string where all occurrences of old have been replaced by new.
  • delimiter.join(list of strings) Returns a new string with all the strings joined by the delimiter

 

# "{0} {1}".format(first, second)

first = "apple"
second = "banana"
third = "carrot"

formatted_string = "{0} {2} {1}".format(first, second, third)   #{} , {} ,{} 인덱스 변수대로 대체 되는 거 인듯 , 맞네. 즉 .format 뒤에 오는 값을 변수로 새겨서 {0},{1}이렇게 사용 가능 하다는 뜻

print(formatted_string)

"""Outputs:
apple carrot banana
"""

 

Formatting expressions

ExprMeaningExample

{:d} integer value '{:d}'.format(10.5) → '10'
{:.2f} floating point with that many decimals '{:.2f}'.format(0.5) → '0.50'
{:.2s} string with that many characters '{:.2s}'.format('Python') → 'Py'
{:<6s} string aligned to the left that many spaces '{:<6s}'.format('Py') → 'Py    '
{:>6s} string aligned to the right that many spaces '{:>6s}'.format('Py') → '    Py'
{:^6s} string centered in that many spaces '{:^6s}'.format('Py') → '  Py '

 

List == []

 

len() function 쓰면 list안에 element 몇개 있는지 확인 가능.

in 쓰면, Boolean으로 list안의 값 확인 가능

 

 

index 넘는거 프린트 하려고 하면 index error나옴

 

 

List는 Mutable 하다

 

append method = 리스트 끝에 add하는거

insert = 리스트 위치 잡아서 거기다가 추가 하는거

remove = 리스트에서 element 지우는거 , 없는 element지우려고 하면 에러남

pop == remove하고 뭐가 remove됬는지 보여줌

fruit[x] = x자리에 element 수정

 

def skip_elements(elements):
    # Initialize variables
    new_list = []
    i = 0

    # Iterate through the list
    for a in elements:
        # Does this element belong in the resulting list?
        if i % 2 == 0:
            # Add this element to the resulting list
            new_list.append(a)
        # Increment i
        i += 1

    return new_list

print(skip_elements(["a""b""c""d""e""f""g"])) # Should be ['a', 'c', 'e', 'g']
print(skip_elements(['Orange''Pineapple''Strawberry''Kiwi''Peach'])) # Should be ['Orange', 'Strawberry', 'Peach']
print(skip_elements([])) # Should be []

i = 0 나누기 2 해가지고, 짝수배열로 리스트 값 append시키게 해서 해결

 

 

파이썬 데이터 타입

 

 

[] 대신 () 이거 씀 

fullname = ('Grace' , 'M' , 'Hopper')

function return 할때 Tuple로 return 함

튜플 데이터 타입일 경우에, index order를 신경 써야함

 

Unpack = 튜플 각각 값을 다른 변수로 저장해서 unpack할수있음 - 다른 3 seperated value

def file_size(file_info):
    name, type, size = file_info
    return("{:.2f}".format(size / 1024))

print(file_size(('Class Assignment''docx'17875))) # Should print 17.46
print(file_size(('Notes''txt'496))) # Should print 0.48
print(file_size(('Program''py'1239))) # Should print 1.21

 

Tuples can be useful when we need to ensure that an element is in a certain position and will not change.

 

Enumerate method는

파이썬의 내장된 기능으로써 리스트 인덱스 요소를 함께 출력할때 사용한다

import time

a = {'coke' : 1000 , 'sprite' : 1000 , 'vita 500': 800, 'cocoparm' : 700 , 'Water' : 600}
b = {'coke' : 1 , 'sprite' : 2 , 'vita 500': 1, 'cocoparm' : 0 , 'Water' : 1}
menu = list(a.items()) # banding machine menu list
stock_list = list(b.values()) # stock list

print(list(enumerate(menu)))

[(0, ('coke', 1000)), (1, ('sprite', 1000)), (2, ('vita 500', 800)), (3, ('cocoparm', 700)), (4, ('Water', 600))]

이렇게 enumerate 쓰면 인덱스 넘버랑 같이 출력 되게 할때 쓰는 기능

요소개수가 많아질수록 편리하게 사용가능

보통 반복문에서 사용 많이함

for e,i in enumerate(menu):
    print(e,i)

0 ('coke', 1000)
1 ('sprite', 1000)
2 ('vita 500', 800)
3 ('cocoparm', 700)
4 ('Water', 600)

 

반복문 쓸때, 변수 2개주고 in 다음 enumerate function 에다가 list 값 넣어주면 저런식으로 출력이 됨

즉 인덱스 번호랑 같이 출력 하고자할때 쓰는거

간단한 반복문 으로 써도 되긴 함


e = 0
for i in menu:
    print(e,i)
    e += 1

보통 이렇게 e라는 변수 주고, 반복 될때마다 1씩 늘어나도록 하는 식으로 사용함

차이점이 있다면 코드 두줄 차이인데, 추후에 프로그램을 짜다보면 리스트에 들어있는것도 많아지고 하다보면 귀찮아짐 = 프로그램이 복잡해짐 , 인덱스 변호 몇번일때.. 뭐 이런거

 

def full_emails(people):
    result = []
    for email, name in people:          #인덱스 갯수 끝날때까지 반복하니까 2번
        result.append("{} <{}>".format(name,email))
    return result

print(full_emails([("Wayne@gmail.com" , "Wayne Ko"), ("Ji@gmail.com" , "Ji Maan Kim")]))

이렇게 people이라는 parameter 변수에,리스트 값으로 넣어서 function 출력 가능

 

The enumerate() function takes a list as a parameter and returns a tuple for each element in the list.

 

List Comparison

List comprehension

x = []
for i in range(1,11):
    x.append(i*7)

print(x)

y = [ x *7 for x in range(1,11)]
print(y)

이렇게 위에꺼랑 다르게 표현 가능

friends = ["Wayne" , "Ji Maan" , "Joshua" , "Young Jase"]
i = [len(x) for x in friends]
print(i)

이렇게 같이 써가지고 값 출력 가능

z = [x for x in range(0,101) if x % 3 == 0]
print(z)
So cool Huh
def odd_numbers(n):
    return [x for x in range(0,n+1if x % 2 == 1]

 

print(odd_numbers(5))  # Should print [1, 3, 5]
print(odd_numbers(10)) # Should print [1, 3, 5, 7, 9]
print(odd_numbers(11)) # Should print [1, 3, 5, 7, 9, 11]
print(odd_numbers(1))  # Should print [1]
print(odd_numbers(-1)) # Should print []

 

Common sequence operations

  • len(sequence) Returns the length of the sequence
  • for element in sequence Iterates over each element in the sequence
  • if element in sequence Checks whether the element is part of the sequence
  • sequence[i] Accesses the element at index i of the sequence, starting at zero
  • sequence[i:j] Accesses a slice starting at index i, ending at index j-1. If i is omitted, it's 0 by default. If j is omitted, it's len(sequence) by default.
  • for index, element in enumerate(sequence) Iterates over both the indexes and the elements in the sequence at the same time

Check out the official documentation for sequence operations.

List-specific operations and methods

  • list[i] = x Replaces the element at index i with x
  • list.append(x) Inserts x at the end of the list
  • list.insert(i, x) Inserts x at index i
  • list.pop(i) Returns the element a index i, also removing it from the list. If i is omitted, the last element is returned and removed.
  • list.remove(x) Removes the first occurrence of x in the list
  • list.sort() Sorts the items in the list
  • list.reverse() Reverses the order of items of the list
  • list.clear() Removes all the items of the list
  • list.copy() Creates a copy of the list
  • list.extend(other_list) Appends all the elements of other_list at the end of list

 

Dictionary

Dictionary using {} Curly Bracket

file_counts = {"jpg" :10 , "txt" :14, "csv" :2 , "py" : 23}

print(file_counts["txt"])
print("jpg" in file_counts)
print("csv" in file_counts)
file_counts["cfg"] = 8
print(file_counts)
file_counts["jpg"] = 1
print(file_counts)
del file_counts["cfg"]
print(file_counts)

PS C:\Users\Wayne Ko\Desktop\Python> & "C:/Users/Wayne Ko/AppData/Local/Programs/Python/Python310/python.exe" "c:/Users/Wayne Ko/Desktop/Python/Google_Python/First.py"       
14
True
True
{'jpg': 10, 'txt': 14, 'csv': 2, 'py': 23, 'cfg': 8}
{'jpg': 1, 'txt': 14, 'csv': 2, 'py': 23, 'cfg': 8}
{'jpg': 1, 'txt': 14, 'csv': 2, 'py': 23}

 

for extention in file_counts:
    print(extention)

jpg
txt
csv
py
이렇게 하면Key 프린트함

 

for ext, amount in file_counts.items():
    print("There are {} files with the . {}".format(amount,ext))

There are 10 files with the . jpg
There are 14 files with the . txt
There are 2 files with the . csv
There are 23 files with the . py

 

이렇게 item () Method 써가지고 Key랑 Value 둘다 출력가능

print(file_counts.keys())
print(file_counts.values())

dict_keys(['jpg', 'txt', 'csv', 'py'])
dict_values([10, 14, 2, 23])

 

def count_letter(text):
    result = {}
    for letter in text:
        if letter not in result:
            result[letter] = 0
        result[letter] += 1
    return result

print(count_letter("Soccer is fun"))
{'S': 1, 'o': 1, 'c': 2, 'e': 1, 'r': 1, ' ': 2, 'i': 1, 's': 1, 'f': 1, 'u': 1, 'n': 1}
 
Dictionary Key have to be "immutable type " , number , tuple, string, booleans
 
wardrobe = {"shirt":["red","blue","white"], "jeans":["blue","black"]}
for cloth,colors in wardrobe.items():
    for color in colors:
        print("{} {}".format(cloth,color))
 
set
 set = key of value but no associate value
 
 

Dictionary Methods Cheat Sheet

Definition

x = {key1:value1, key2:value2}

Operations

  • len(dictionary) - Returns the number of items in the dictionary
  • for key in dictionary - Iterates over each key in the dictionary
  • for key, value in dictionary.items() - Iterates over each key,value pair in the dictionary
  • if key in dictionary - Checks whether the key is in the dictionary
  • dictionary[key] - Accesses the item with key key of the dictionary
  • dictionary[key] = value - Sets the value associated with key
  • del dictionary[key] - Removes the item with key key from the dictionary

Methods

  • dict.get(key, default) - Returns the element corresponding to key, or default if it's not present
  • dict.keys() - Returns a sequence containing the keys in the dictionary
  • dict.values() - Returns a sequence containing the values in the dictionary
  • dict.update(other_dictionary) - Updates the dictionary with the items coming from the other dictionary. Existing entries will be replaced; new entries will be added.
  • dict.clear() - Removes all the items of the dictionary
 
 
 
 

python dictionary 에서 

item method = 딕셔너리값 item으로 묶어주는거 ()

value method = 딕셔너리안의 키값 만 묶어주는거 ()

comprehension = 이해력

horn = 뿔

fin = 지느러미

tentacle = 촉수

 

 

 

 

enumerate == 열거하다

 

 

 

 

 

 

corresponding = 해당하는, 상응하는

palindrome = 뒤에서 읽으나 앞에서 읽으나 똑같은구문