데이터 형식 이해 및 문자열 조작 방법

JOOYEUN SEO·2024년 8월 12일

100 Days of Python

목록 보기
2/76
post-thumbnail

❖ 기본 데이터 형식

◇ String

  • Day1. Strings 참고
  • Sub-script
    • 문자열을 분해해서 원하는 특정 문자를 추출하는 방법
    • 대괄호 안의 숫자로 문자열의 어떤 문자를 추출할 지 결정(숫자는 항상 0부터 시작)
    • ...○○○"Ⓗⓔⓛⓛⓞ"○○○...에서
      "Hello"[0] = H
      "Hello"[4] = o

◇ Integer

  • 소수점 이하가 없는 정수형 데이터
  • 다른 것 없이 숫자만 사용 (따옴표 안에 있으면 문자열이니 주의)
  • Large Integer
    • 큰 숫자에 천 단위로 쉼표를 넣어 쉽게 읽는 것과 같음
    • 파이썬에서는 쉼표 대신 밑줄 사용 (컴퓨터는 _를 인식 안 함)

◇ Float

  • 소수점이 있는 실수형 데이터
  • 부동 소수점(Floating Point Number)의 줄임말

◇ Boolean

  • True(T), False(F) 의 2가지 값만 가짐
  • 무언가가 인지, 거짓인지를 테스트하는데 많이 쓰임

❖ 형식 오류

# 문자열에 정수를 연결
num_char = len(input("what is your name?"))
print("your name has " + num_char + " characters.")
what is your name?❚Angela
TypeError: can only concatenate str (not "int") to str (형식 확인 필요)

◇ type()

  • 괄호 안의 데이터가 어떤 형식인지 알려주는 함수

type( data )

num_char = len(input("what is your name?"))
print(type(num_char))
what is your name?❚Angela
<class 'int'>

❖ 형 변환

형 변환 함수 : 변환하려는 형식(형 변환을 하려는 데이터)

  • str( data ) : 괄호 안의 객체를 문자열로 변경
    num_char = len(input("what is your name?"))
     new_num_char = str(num_char)    # 정수를 문자열로 변환
     print("your name has " + new_num_char + " characters.")
    what is your name?❚Angela
    your name has 6 characters.
  • chr( data ) : 괄호 안의 객체(정수 1개)를 그에 대응하는 유니코드 문자로 변경
  • int( data ) : 괄호 안의 객체를 정수로 변경
  • float( data ) : 괄호 안의 객체를 실수로 변경
    print(70 + float("100.5"))	# 70이 자동으로 70.0으로 변환되어 덧셈 계산
    170.5
  • bool( data ) : 괄호 안의 객체를 bool 타입으로 변경
    print(bool(""))       # 빈 문자열 : False
     print(bool("0"))      # 내용이 있는 문자열 : True
     print(bool(0))        # 숫자 0 : False
     print(bool(-12.56))   # 0 이외의 숫자 : True
    False
    True
    False
    True

💯 AUDITORIUM coding exercises

Data Types
입력값에서 십의 자리의 숫자와 일의 자리 숫자를 더한 값을 구하는 프로그램

two_digit_number = input()
first_digit = int(two_digit_number[0])
second_digit = int(two_digit_number[1])
print(first_digit + second_digit)
12

❖ 수학 연산

◇ 기본 연산

print(3 + 9)    # 덧셈
print(7 - 4)    # 뺄셈
print(5 * 2)    # 곱셈
print(6 / 3)    # 나눗셈 (항상 float 형태로 출력)
print(2 ** 2)   # 거듭제곱
12
3
10
2.0
4

◇ 연산 우선순위

  • 같은 줄의 코드에 두 번 이상의 연산을 할 때 우선순위가 적용
  • PEMDAS + LR
    • Parentheses (괄호)
      • Ecponents (지수)
        • Multiplication (곱셈)
        • Division (나눗셈)
          • Addition (덧셈)
          • Subtraction (뺄셈)
    • 같은 우선순위끼리는 왼쪽에서 오른쪽 순으로 계산됨(L→R)

💯 coding exercises

BMI Calculator
BMI를 계산하는 프로그램

  • 계산 공식 : BMI=weight(kg)height2(m2)BMI=\frac{weight(kg)}{height^2(m^2)}
height = input()
weight = input()

BMI = float(weight) / float(height) ** 2
print(int(BMI))
1.65
72
26

❖ 소수점 처리

◇ 반올림

  • round( data [, n] ) : 1번째 인자로 받은 숫자를 반올림하는 함수
    • 2번째 인자가 없을 경우 : 정수로 반올림 (출력 시 정수.0 의 float형)
    • 2번째 인자로 숫자 nn을 받은 경우 : 소수점 nn째 자리로 반올림
print(round(2.66666666, 2))
print(round(8 / 3, 2))
#
2.67

#
2.67

◇ 올림

  • math.floor( x )
    • math 모듈
    • x보다 크거나 같은 가장 작은 정수로 올림
    • int값 반환

◇ 내림, 버림

  • //
    • 나눗셈의 을 구하는 연산자로, 소수점 뒤의 모든 숫자를 버림
      (해당 실수 이하의 최대 정수를 구하기 때문에 음수의 경우 주의)
    • int // int : int 반환
      float // int, int // float, float // float : float(정수.0) 반환
  • math.floor( x )
    • math 모듈
    • x보다 작거나 같은 가장 큰 정수로 내림
  • math.trunc( x )
    • math 모듈
    • x의 소수점 아래 숫자를 버림

◇ 서식 지정 표현식

형식 예시
format( data, ".nf" ) 또는 "{:.nf} {:.nf} …".format( data1, data2… )

print('{:.0f}'.format(10.05))	  # 소수점 첫째자리를 반올림하여 정수값 반환
print('{:.3f}'.format(0.0543))	  # 소수점 셋째자리까지만 반환
print('{:.3g}'.format(0.0543)) 	  # 유효숫자 3개까지만 반환
print('{:.2s}'.format('Python'))  # 문자열의 앞 2글자까지만 반환
print('{:<6s}'.format('Py'))	  # 문자열을 6칸에 맞춰 왼쪽 정렬
print('{:>6s}'.format('Py'))	  # 문자열을 6칸에 맞춰 오른쪽 정렬
print('{:^6s}'.format('Py'))      # 문자열을 6칸에 맞춰 중앙에 정렬

print("{} {:.2s} {:.1f}".format("apple", "banana", 3.14)) # 여러 값 혼합
[ 출력 결과 ]

10
0.054
0.0543
Py
Py    
    Py
  Py
apple ba 3.1

❖ 할당 연산자

이전 값에 기반해서 계속 연산을 할 수 있음

score = 4

score += 1    # score = score + 1 과 동일
print(score)
score -= 1    # score = score - 1 과 동일
print(score)
score *= 2    # score = score * 2 와 동일
print(score)
score /= 2    # score = score / 2 와 동일
print(score)
score **= 2   # score = score ** 2 와 동일
print(score)
score //= 2   # score = score // 2 와 동일
print(score)
5
4
8
4.0
16.0
8.0

❖ F-String

  • 문자열에 다양한 데이터 유형을 쉽게 혼합하는 방법
    1. 문자열 앞에 f 를 붙임 (문자열은 보통 큰따옴표로 작성하는 것을 선호)
    2. 문자열 안에 { } (중괄호)를 넣고, 여기에 다른 타입의 데이터 추가

💯 coding exercises

Life in Weeks
90살까지 산다고 가정했을 때, 남은 주(week) 수를 계산하는 프로그램

age = input()

years = 90 - int(age)		# 남은 년수를 계산
weeks = years * 52			# 1년 = 52주

print(f"You have {weeks} weeks left.")
30
You have 3120 weeks left.

🗂️ Day2 프로젝트: 팁 계산기

청구 금액에 팁을 추가한 총 금액을 여러 명이서 똑같이 나눠 낼 때, 1인당 지불해야 하는 돈을 계산하는 프로그램

🔍 유의 사항

  • 팁은 백분율
    • 예시) 나온 금액에 팁 12%를 더한 총액
      1. 팁 = 금액 * (12 / 100), 총액 = 금액 + 팁
      2. 총액 = 금액 * 1.12
        (1번과 거의 같은 결과지만 더 간단히 계산 가능)
  • 최종 금액은 소수점 둘째 자리까지만 계산하면 됨
    • 정수 또는 소수점 첫째 자리까지만 있는 경우에도 소수점 둘째 자리까지 있는 것이 보기 편함
    • 예시) 12는 12.00로, 12.4는 12.40로 0을 넣어 소수점 둘째 자리로 통일
    • round() 함수로는 자리수를 맞추는 것이 불가능하므로, format() 함수 이용하기
    • 참고 링크

⌨️ 작성한 코드

#If the bill was $150.00, split between 5 people, with 12% tip. 
#Each person should pay (150.00 / 5) * 1.12 = 33.6
#Format the result to 2 decimal places = 33.60
#Write your code below this line 👇
print("welcome to the tip calculator.")

bill = float(input("what was the total bill? $"))
tip = int(input("what percentage tip would you like to give? (10, 12, 15) "))
people = int(input("how many people to split the bill? "))

bill_per_person = (bill / people) * (1 + (tip / 100))

final_amount = round(bill_per_person, 2)
#If you want the final_amount to always have 2 decimal places.
#e.g. $12 becomes $12.00
#This is how you can implement it:
final_amount = "{:.2f}".format(bill_per_person)

print(f"each person should pay : ${final_amount}")
welcome to the tip calculator.
what was the total bill? $❚256.78
what percentage tip would you like to give? (10, 12, 15) ❚15
how many people to split the bill? ❚3
each person should pay : $98.43




▷ Angela Yu, [Python 부트캠프 : 100개의 프로젝트로 Python 개발 완전 정복], Udemy, https://www.udemy.com/course/best-100-days-python/?couponCode=ST3MT72524

0개의 댓글