달나라 노트

Python Basic : bytes(string을 bytes type으로 변경, bytes type 데이터 생성, convert string to bytes) 본문

Python/Python Basic

Python Basic : bytes(string을 bytes type으로 변경, bytes type 데이터 생성, convert string to bytes)

CosmosProject 2023. 10. 18. 22:55
728x90
반응형

 

 

 

Python 내장 함수 bytes() method는 string type data를 bytes type data로 바꿔줍니다.

 

buytes() method는 python의 built-in function(내장 함수)이기 때문에 별도의 library import가 필요 없습니다.

 

 

 

Syntax

bytes(value, encoding)

 

bytes() method는 2개의 parameter를 받습니다.

 

- values

bytes type으로 변환할 값입니다.

 

- encoding

어떤 encoding을 사용할건지에 대한 값입니다.

주로 utf-8을 입력합니다.

 

 

 

 

 

str_test = 'I like apple.'
bytes_test = bytes(str_test, 'utf-8')
print(str_test)
print(type(str_test))

print(bytes_test)
print(type(bytes_test))



-- Result
I like apple.
<class 'str'>

b'I like apple.'
<class 'bytes'>

 

위 예시는 'I like apple.' 이라는 string을 bytes type으로 바꾸는 예시입니다.

 

bytes type의 값을 출력한 결과를 보면 b'I like apple.'와 같은 것을 알 수 있습니다.

이처럼 bytes type data를 출력하면 앞에 b가 붙어서 bytes type임을 나타내줍니다.

 

 

 

 

 

list_test = [1, 2, 'a', 'b', '5']

str_test = str(list_test)
print(str_test)
print(type(str_test))

bytes_test = bytes(str_test, 'utf-8')
print(bytes_test)
print(type(bytes_test))


-- Result
[1, 2, 'a', 'b', '5']
<class 'str'>

b"[1, 2, 'a', 'b', '5']"
<class 'bytes'>

 

python list도 bytes type으로 바꿀 수 있습니다.

 

- str_test = str(list_test)

list를 생성한 후 list를 먼저 string으로 바꿉니다.

 

 

- bytes_test = bytes(str_test, 'utf-8')

그리고 string으로 바뀐 list를 bytes로 바꿔주면 됩니다.

 

 

 

 

import pandas as pd
from io import StringIO

dict_test = {
    'id': [1, 2, 3, 4, 5],
    'name': ['banana', 'apple', 'melon', 'peach', 'grape'],
    'price': [3500, 16000, 15000, 25000, 5800]
}

df_test = pd.DataFrame(dict_test)
print(df_test)

list_test = df_test.values.tolist()
print(list_test)
print(type(list_test))

str_test = str(list_test)
print(str_test)
print(type(str_test))

bytes_test = bytes(str_test, 'utf-8')
print(bytes_test)
print(type(bytes_test))



-- Result
   id    name  price
0   1  banana   3500
1   2   apple  16000
2   3   melon  15000
3   4   peach  25000
4   5   grape   5800

[[1, 'banana', 3500], [2, 'apple', 16000], [3, 'melon', 15000], [4, 'peach', 25000], [5, 'grape', 5800]]
<class 'list'>

[[1, 'banana', 3500], [2, 'apple', 16000], [3, 'melon', 15000], [4, 'peach', 25000], [5, 'grape', 5800]]
<class 'str'>

b"[[1, 'banana', 3500], [2, 'apple', 16000], [3, 'melon', 15000], [4, 'peach', 25000], [5, 'grape', 5800]]"
<class 'bytes'>

 

이를 이용하면 DataFrame 데이터를 bytes로 바꿀 수도 있습니다.

 

- list_test = df_test.values.tolist()

DataFrame에 있는 데이터를 모두 list로 바꿉니다.

 

- str_test = str(list_test)

list를 string으로 변환합니다.

 

- bytes_test = bytes(str_test, 'utf-8')

string을 bytes로 변환합니다.

 

되게 간단하죠?

 

 

 

 

 

import pandas as pd
from io import StringIO

dict_test = {
    'id': [1, 2, 3, 4, 5],
    'name': ['banana', 'apple', 'melon', 'peach', 'grape'],
    'price': [3500, 16000, 15000, 25000, 5800]
}

df_test = pd.DataFrame(dict_test)
print(df_test)

csv_io = StringIO()
df_test.to_csv(csv_io, index=False)
print(csv_io)

csv_values = csv_io.getvalue()
print(csv_values)
print(type(csv_values))


bytes_values = bytes(csv_values, 'utf-8')
print(bytes_values)
print(type(bytes_values))



-- Result
   id    name  price
0   1  banana   3500
1   2   apple  16000
2   3   melon  15000
3   4   peach  25000
4   5   grape   5800

<_io.StringIO object at 0x7fbe0809bd90>

id,name,price
1,banana,3500
2,apple,16000
3,melon,15000
4,peach,25000
5,grape,5800
<class 'str'>

b'id,name,price\n1,banana,3500\n2,apple,16000\n3,melon,15000\n4,peach,25000\n5,grape,5800\n'
<class 'bytes'>

 

위 예시는 StringIO를 이용해 DataFrame을 comma separate csv type string으로 변환한 후 그것을 bytes type data로 변환한 것입니다.

 

- StringIO 관련 내용 = https://cosmosproject.tistory.com/787

 

Python io : StringIO (comma separate csv type string 생성, DataFrame을 csv type string으로 변환하기)

아래와 같은 DataFrame이 있다고 생각해봅시다. import pandas as pd from io import StringIO dict_test = { 'id': [1, 2, 3, 4, 5], 'name': ['banana', 'apple', 'melon', 'peach', 'grape'], 'price': [3500, 16000, 15000, 25000, 5800] } df_test = pd.D

cosmosproject.tistory.com

 

 

 

 

 

 

728x90
반응형
Comments