Skip to content

kobic 차세대 생명정보 교육 파이썬기초편 2강 #
Find similar titles

파이썬 기초편 2강. 파이썬 기본 자료형 #

실습코드 #

파이썬 변수 #

#!python
>>> one = 'hello!'
>>> two = 'hello! hello!'
>>> three = 3

>>> one, two, three = 'hello!', 'hello! hello!', 3
>>> one
'hello!'
>> three
3

숫자형 #

#!python
# 정수
>>> a = 10
>>> print(x, "is of type", type(x))

# 실수
>>> a = 4.0
>>> print(x, "is of type", type(x))

# 복소수
>>> a = 1+3j
>>> print(x, "is complex number?", isinstance(1+3, complex))

숫자형 진접변환 #

#!python
# 2진수로 변환 (접두어 '0b')
>>> x = 200
>>> bin(x)
'0b11001000'

# 8진수로 변환 (접두어 '0o')
>>> oct(x)
'0o310'

# 16진수로 변환 (접두어 '0x')
>>> hex(x)
'0xc8'

숫자형 형변환 #

#!python
# 실수 -> 정수로 변환
>>> int(2.9999)
2
>>> int(-2.9999)
-2

# 정수 -> 실수로 변환
>>> float(100)
100.0
>>> float(-100)
-100.0

# 복소수는 정수, 실수로 변환할 수 없음
>>> int(1+5j)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't convert complex to int

>>> float(1+5j)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't convert complex to float

숫자형 연산 #

#!python
# 덧셈
>>> 1 + 2
3
>>> -1.3232 + 2
0.6768000000000001
>>> 232.2 + 355.4
587.5999999999999

# 뺄셈
>>> 1 - 2
-1
>>> 122.543 - 100
22.543000000000006
>>> 10+5j - 122.3
(-112.3+5j)

# 곱셈
>>> 2 * 5
10
>>> 2.2 * -0.5
-1.1
>>> 5+6j * 4+5j
(5+29j)

# 지수
>>> 10**2
100
>>> 10**-2
0.01

# 나눗셈
>>> 500/5
100.0
>>> 503.55/5
100.71000000000001

# 나눗셈의 몫
>>> 503.55//5
100.0

# 나눗셈의 나머지
>>> 503.55%5
3.5500000000000114

문자열 #

#!python
# 문자열 선언
>>> 'Hello World'
'Hello World'
>>> "Hello"
'Hello'

# 여러줄의 문자열 선언
>>> """This is
... python string"""
'This is\npython string

# 따옴표가 포함된 문자열
>>> 'It\'s good!'     # 역슬래시(\)사용
"It's good!"
>>> "It's good!"
"It's good!"

문자열연산 #

#!python
# 문자열 합치기
>>> a = 'Beautiful is '
>>> b = 'better than ugly.'
>>> a + b
'Beautiful is better than ugly.'

# 문자열 곱하기
>>> a * 3
'Beautiful is Beautiful is Beautiful is '

문자열 인덱싱 #

#!python
>>> a = "Monty Python"
>>> a[0]
'M'
>>> a[-1]
'n'
>>> a[6]
'P'
>>> a[-6]
'P'
# 문자열의 내용은 바꿀 수 없다
>>> a[6] = 'X'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

문자열 슬라이싱 #

#!python
>>> a = 'Monty Python'
>>> a[0:2]
'Mo'
>>> a[-5:-2]
'yth'
>>> a[-2:]   # 끝값을 생략하면 마지막글자까지 나옴
'on'
>>> a[:5]    # 처음값을 생략하면 첫글자부터 나옴 
'Monty'
>>> a[:]
'Monty Python'
>>> a[::-1]    # 역순으로 나옴
'nohtyP ytnoM'
>>> a[0:10:2]   # 0~10까지의 문자를 2문자씩 건너서 가져옴
'MnyPt'

문자열에서 제공하는 다양한 기능 #

#!python
>>> a = '    Monty Python '
>>> a.find('P')
>>> a.upper()
>>> a.lower()
>>> a.count('X')
>>> a.count('Py')
>>> a.strip()
>>> a.lstrip()
>>> a.rstrip()
>>> a.replace('Monty ', 'I love ')
>>> lower_a = a.lower()
>>> lower_a.title()
>>> len(a)
>>> len(a.strip())

문자열 포맷팅 (old way) #

#!python
>>> print("%s is better than %s." % ('Simple', 'complex'))
Simple is better than complex.
>>> print("%s is better than %s." % ('Flat', 'nested'))
Flat is better than nested.
>>> print("%4.2f + %f = %d" % (1.1, 2.2, 1.1 + 2.2))
1.10 + 2.200000 = 3

문자열 포맷팅 (new way) #

#!python
>>> print("{} is better than {}.".format('Simple', 'complex'))
Simple is better than complex.

>>> print("{0:4.2f} + {1:6.5f} = {2:1.0f}".format(1.1, 2.2, 1.1 + 2.2))
1.10 + 2.20000 = 3

# 연습문제# 일반적인 포맷팅 1
>>> print("{} is better than {}.".format('Simple', 'complex'))
Simple is better than complex.

# 순서를 이용한 포맷팅 2
>>> print("{0} is better than {1}.".format('Simple', 'complex'))
Simple is better than complex.

# 필드명을 이용한 포맷팅 3
>>> print("{a} is better than {b}.".format(a='Simple', b='complex'))
Simple is better than complex.

# 인덱스를 이용한 포맷팅 4
>>> vals = ('Simple', 'complex')
>>> print("{x[0]} is better than {x[1]}.".format(x=vals))
Simple is better than complex.

연습문제 #

1번 #

문자열 x = 'Now is better than never.'을 인덱싱, 슬라이싱, 다양한 기능 등을 사용하여 주어진 형태로 만드시오.

  • 'now is better than never.'
  • 'never'
  • 'Now Is Better Than Never.'
  • '.reven'
  • 'Now-is-better-than-never.'
  • 't' 갯수 세기
  • x의 길이

2번 #

문자열 포맷팅을 이용하여 다음 문장을 출력하시오. ('Simple'과 'complex'에 포맷팅 사용)

Simple is better than complex.
  1. '%'를 이용한 방법
  2. format()을 이용한 방법

연습문제 풀이 #

1번 #

#!python
>>> a.lower()
'now is better than never.'
>>> a.title()
'Now Is Better Than Never.'
>>> a[::-1][:6]
'.reven'
>>> a.replace(' ', '-')
'Now-is-better-than-never.'
>>> a.count('t')
3
>>> len(a)
25

2번 #

#!python
# '%'사용
>>> print("%s is better than %s." % ('Simple', 'complex'))
Simple is better than complex.

# format()사용
>>> print("{} is better than {}.".format('Simple', 'complex'))
Simple is better than complex.
0.0.1_20210630_7_v33