본문 바로가기
Python

[Python] Data type (1)

1. 숫자 자료형 Number data type


숫자 자료형 안에도 여러 종류가 있으나, 그 중 가장 많이 쓰는 자료형은 정수형과 실수형임

There are many types of numerical data types, but the most commonly used data types are integer and real numbers

 

1-1). 정수형 (Integer, int) 

- 말 그대로 정수를 뜻하는 자료형

A data type that literally means an integer

# [Tip] 자료형을 찍을 때 쓰는 함수 : type()
type(0)

 

2-1. 실수형 (Float, float)

- 소수점이 포함된 숫자

Numbers with decimal points

type(0.0)

 

 

2. 숫자 연산 / 복합 대입 연산자 Arithmetic Operator / Assignment Operator


숫자 연산자 Arithmetic Operator

+ : 덧셈 addition
- : 뺄셈 subtraction
* : 곱셈 Multiplication
/ : 나눗셈 division
// : 나눗셈 몫 (정수형) Share of division (integer type)
% : 나눗셈 나머지 the rest of the division
** : 제곱 square

 

 

2-1) 숫자 연산 Arithmetic Operator


# 정수 + 정수

integer +  integer

1 + 2
->3

 

# 실수 + 실수

real number + real number

1.0 + 2.0
->3.0

 

# 정수 + 실수

integer + real number

1 + 2.0
->3.0

 

# 다른 연산자

Other operators

2.0 ** 3
->8.0

이때, 실수와 정수를 교차로 사용했기 때문에 더 큰 범위인 실수가 출력이 됨

At this point, if real numbers and integers are used intersectionally, real numbers are output because real numbers are a larger range

 

 

# 변수에 숫자를 할당하고 계산

Assigning numbers to variables and calculating

a = 5  # 번역 : a에 5를 할당한다.
b = 4  # 번역 : b에 4를 할당한다.
a * b  # 번역 : a와 b를 곱하라
->20

 

 

2-2) 복합 대입 연산자 Assignment Operator


  • 복합 대입 연산자는 연산과 할당을 합쳐 놓은 것 Assignment Operator is a combination of operations and assignments
  • 간결한 식을 위해서 사용 Use for concise expressions
  • 자주 쓰임 Frequently used

 

# 원래 대입식

original assignment expression

a = n
a = a + n
print(a)

 

# 복합 대입 연산자 (더하기)

Assignment Operator (Addition)

a = 7
a += 1
print(a)

 

# 복합 대입 연산자 (곱셈)

Assignment Operator (Multiplication) 

b = 5
b *= 2
print(b)

 

# 복합 대입 연산자 (나눗셈 몫)

Assignment Operator (Share of division)

c = 10
c //= 3 # 나누기 몫(//),  나머지(%)
print(c)

 

# 복합 대입 연산자 (제곱)

Assignment Operator (Square)

d = 3
d **= 4
print(d)

 

 

3. 문자열 자료형 (String, str)


3.1) 문자열 string

  • 따옴표에 둘러싸여 있으면 => 문자열
    if enclosed in quotation marks => String
"안녕하세요, 저는 줴이든입니다."
'7'
"""월을"""
'''좋아해요'''

 

3.2) 문자열 만드는 4가지 방법 4 Ways To Create Strings

(1) 큰 따옴표(")에 둘러싸기 Enclosing in quotation marks (")
(2) 작은 따옴표(')에 둘러싸기 Enclosing in small marks (')
(3) 큰 따옴표 연속 3개(""")에 둘러싸기 Enclosing three consecutive quotes (""")
(4) 작은 따옴표 연속 3개(''')에 둘러싸기 Enclosing 3 consecutive quotes ('')

 

 

# 큰 따옴표(")에 둘러싸기

Enclosing in quotation marks (")

"안녕하세요, 저는 줴이든입니다."

 

# 작은 따옴표(')에 둘러싸기

Enclosing in small marks (')

'일곱'

 

# 큰 따옴표 연속 3개(""")에 둘러싸기

Enclosing three consecutive quotes (""")

"""월요일"""

 

# 작은 따옴표 연속 3개(''')에 둘러싸기

Enclosing 3 consecutive quotes ('')

'''좋아해요'''

 

 

✔️문자열 자료형 만드는데 왜 네 가지의 방법이나 필요한 이유The reason why Four ways to create a string data type

 

1. 여러 줄인 문자열을 변수에 대입하고 싶을 때

To substitute multiple abbreviated strings into a variable

 

(1) 연속된 작은 따옴표 3개 또는 큰 따옴표 3개를 사용

Use 3 consecutive small quotes or 3 large quotes

# 작은 따옴표 3개로 감싸기
multiline = '''
Only I can change my life,
no one can do it for me.'''

print(multiline)
# 큰 따옴표 3개로 감싸기
multiline = """Only 
I can change my life,
no one can do it 
for me."""

print(multiline)

 

(2) 이스케이프 코드(확장열) 사용하기

Enable escape code (extended column)

# `\n` : 줄 바꿈 이스케이프 코드
multiline = 'Only I can change my life,\nno one can do it for me'

print(multiline)

 

 

2. 문자열 안에 작은 따옴표나 큰 따옴표를 포함시키고 싶을 때

To include a small quotation mark or a large quotation mark in a string

 

(1) 겹치지 않는 따옴표로 둘러싸기

Enclosed in nonoverlapping quotation marks

# 작은 따옴표를 포함한 문자열을 큰 따옴표로 둘러싸기
present = "Don't dwell on the past."

print(present)
# 큰 따옴표를 포함한 문자열은 작은 따옴표로 둘러싸기
answer = '"Do not worry!"'

print(answer)

 

(2) 이스케이프 코드(확장열) 사용하기

Enable escape code (extended column)

# 큰 따옴표와 작은 따옴표 둘 다 나타내고 싶을 때는 이스케이프 코드를 사용
answer = '\"Don\'t worry!\"'

print(answer)

 

 

3.3) 이스케이프 코드 Escape code

  • 이스케이프 코드는 프로그래밍 할 때 문자열 안에 담기 힘든 문자를 사용할 수 있도록 미리 정의해 둔 문자 조합 Escape code is a predefined combination of characters to allow for the use of characters that are hard to program
  • 이스케이프 코드, 확장열이라고 함
    Also known as escape code or extension column

 

# `\t` 예시
tabline = 'thirty\tone'
print(tabline)
# `\` 예시  
# 가독성이 좋게 3줄로 표시되어 있지만
# 한 줄의 문자열로 정의된다.
s = '동짓달 기나긴 밤을 한 허리를 베어내어 \
봄바람 이불 아래 서리서리 넣었다가 \
정든 임 오신 날 밤이거든 굽이굽이 펴리라'

print(s)

 

 

4. 문자열 다루기 Handling strings


1) 문자열 연산 character string operations

 

(1) 문자열 더하기 (= 문자열 연결하기) 

        Add string (= Connect string)

  • 문자열에서 +연산자는 더하기 보다 연결의 의미
    In a string, the + operator means the connection rather than the addition
head = '꾸준히'
tail = 'python'

print(head + tail)
>>>꾸준히python

 

추가적으로, 공백에도 더하기를 더해줄 수 있다.

Additionally, You can also add addition to the blanks.

print(head + ' ' + tail)
->>>꾸준히 python

 

 

(2) 문자열 곱하기

       String multiplication

print('hey' * 10)
>>>heyheyheyheyheyheyheyheyheyhey

 

문자열에 공백을 추가하면 공백이 포함된 채로 출력된다.

Adding a space to a string leaves the space included.

print('hey ' * 10)
>>>hey hey hey hey hey hey hey hey hey hey
 

 

모든 문자열을 곱할 수 있다.

All strings can be multiplied.

print('=' * 50)
print('My Assignment')
print('=' * 50)
>>>
==================================================
My Assignment
==================================================

 

 

(3) 정수와 문자열을 더할 수 있을까? Can we add integers and strings?

 

" + " 연산자는 피연산자의 타입을 판별하여 숫자에 대해서는 덧셈을 하고 문자열에 대해서는 연결

" +' "operator determines the type of operand and add if its type is integer, connect if its string type

a = 7
b = 'lucky'
print(a + b)
>>>
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/tmp/ipykernel_13/500563772.py in <module>
      2 a = 7
      3 b = 'lucky'
----> 4 print(a + b)

TypeError: unsupported operand type(s) for +: 'int' and 'str'

위와 같이 str과 int는 더할 수 없다고 에러가 뜸

As above, the error says you can't add string and integer

 

즉 숫자와 문자열 사이에서는 + 연산자를 쓸 수 없음

That is, the + operator cannot be written between a number and a string

 


그럼에도 쓰고 싶다면 자료형을 일치시키고 쓸 수 있음

If you still want to use it, you can match the data type

print(str(1988) + ' Seoul Olympic')
>>>1988 Seoul Olympic

 

 

 

2) 문자열 길이 구하기 Find the length of strings

  • 자주 쓰임 Frequently used
  • 문자열 외에도 쓰임 Used in addition to strings
  • len() 함수를 사용해서 구할 수 있음 It can be obtained using the len() function
a = 'life'
len(a)
>>>4

 

문자열에 공백이 있을 경우, 공백 또한 포함한 길이를 구함

If the string contains spaces, The spaces are also included in the length

a = ' life '
len(a)
>>>6

 

 

3) 문자열 인덱싱 String Indexing

  • 인덱싱이란 무엇인가를 가리킨다는 의미 Indexing means something
  • 인덱싱 번호를 주의 Watch for indexing numbers
  • []괄호 안에 인덱싱 번호를 넣어서 인덱싱할 수 있음 You can index by putting the indexing number in the brackets
  • 0과 -0은 똑같기 때문에 a[0]와 a[-0]은 동일한 값을 보여줌 Since 0 and -0 are the same, a[0] and a[-0] show the same value
  • 문자열이 길 때, 뒤에서 세는 인덱싱을 자주 사용함
    When the string is long, you often use the backward-counting index

 

# a[0]와 a[-0]은 동일한 값

a[0] and a[-0] have the same value

a = 'python'
a[0], a[-0]
>>>('p', 'p')

 

# 문자열이 길 때, 뒤에서 세는 인덱싱을 자주 사용

When the string is long, you often use the backward-counting index

a = 'Where there is a will there is a way'
a[-3]
>>>'w'

 

 

4) 문자열 슬라이싱 String slicing

  • 슬라이싱(Slicing)은 무엇인가를 잘라낸다는 의미 Slicing means cutting something out
  • 한 문자가 아닌 단어를 뽑아낼 수 있음 You can extract words that are not one character.
  • a[시작 번호:끝 번호+1]로 잘라냄 Cut to a [start number: end number +1]
  • 인덱싱과 마찬가지로 마이너스 기호를 사용 Use minus signs just like indexing
  • 슬라이싱 앞부분을 생략하면 처음부터 뽑아냄 
    If you omit the front part of the slicing, you pull it out from the beginning
  • 슬라이싱 뒷부분을 생략하면 끝까지 뽑아냄 If you omit the back of the slicing, pull it out until the end

# a[시작 번호:끝 번호+1]

[start number: end number +1]

# 0부터 4까지 슬라이싱 하고 싶으면 [0:5]로 표시해야 된다.
a = 'Where there is a will there is a way'
a[0:5]
>>>'Where'

 

# 음수일때

when it's negative

a = 'Where there is a will there is a way'
a[-8:-6]
>>>'is'

 

# 슬라이싱 앞부분을 생략하면 처음부터 뽑아냄

If you omit the front part of the slicing, you pull it out from the beginning

a = 'Where there is a will there is a way'
a[:5]
>>>'Where'

 

# 슬라이싱 뒷부분을 생략하면 끝까지 뽑아냄

If you omit the back of the slicing, pull it out until the end

a = 'Where there is a will there is a way'
a[-3:]
>>>'way'

 

5) 문자열 바꾸기 Replace String

  • 문자열 안의 문자열을 다른 문자열을 바꿀 때는 replace()함수를 사용
    Use the replace() function to replace a string in a string with another string
`기존문자열.replace('바꿀문자열', '새문자열')`

 

# 예시

Example

a = 'Hello, world!'
b = a.replace('world', 'Python')
b
>>>'Hello, Python!'

 

'Python' 카테고리의 다른 글

[Python] Loop  (0) 2023.10.04
[Python] Conditional statement  (1) 2023.10.03
[Python] Data type (3)  (0) 2023.09.28
[Python] Data type (2)  (0) 2023.09.26
[Python] Basics and Terms  (0) 2023.09.21