logo

파이썬 | 문자열을 바이트로 변환

상호 변환은 평소와 같이 매우 인기가 있지만, 파일 처리 또는 기계 학습(Pickle File)을 위해 문자열을 바이트로 변환해야 하는 경우가 많기 때문에 요즘에는 문자열을 바이트로 변환하는 것이 더 일반적입니다. 이것이 수행될 수 있는 특정 방법에 대해 논의해 보겠습니다.

방법 #1: bytes(str, enc) 사용 일반 바이트 함수를 사용하여 문자열을 바이트로 변환할 수 있습니다. 이 함수는 내부적으로 문자열을 지정된 인코딩으로 변환하기 위한 인코딩 함수를 암시적으로 호출하는 CPython 라이브러리를 가리킵니다.



파이썬3

자바 문자열의 값






# Python code to demonstrate> # convert string to byte> # Using bytes(str, enc)> # initializing string> test_string>=> 'GFG>is> best'> # printing original string> print>('The original string : '>+> str>(test_string))> # Using bytes(str, enc)> # convert string to byte> res>=> bytes(test_string,>'utf-8'>)> # print result> print>('The byte converted string>is> : '>+> str>(res)>+> ',>type> : '>+> str>(>type>(res)))>



>

>

출력 :

The original string : GFG is best The byte converted string is : b'GFG is best', type :>

방법 #2: encode(enc) 사용 이 특정 작업을 수행하는 데 가장 권장되는 방법은 인코딩 함수를 사용하여 변환을 완료하는 것입니다. 특정 라이브러리에 대한 추가 링크를 하나 줄이므로 이 함수가 이를 직접 호출합니다.

파이썬3




# Python code to demonstrate> # convert string to byte> # Using encode(enc)> # initializing string> test_string>=> 'GFG>is> best'> # printing original string> print>('The original string : '>+> str>(test_string))> # Using encode(enc)> # convert string to byte> res>=> test_string.encode(>'utf-8'>)> # print result> print>('The byte converted string>is> : '>+> str>(res)>+> ',>type> : '>+> str>(>type>(res)))>

>

>

출력 :

The original string : GFG is best The byte converted string is : b'GFG is best', type :>

방법 #2: memoryview() 사용

이 예에서는 my_string 변수에 대해 encode() 메서드를 호출하여 UTF-8 인코딩을 사용하여 이를 바이트로 변환합니다. 그런 다음 결과 바이트열 객체를 memoryview() 함수에 전달합니다. 이 함수는 기본 바이트의 보기를 제공하는 메모리 보기 객체를 반환합니다.

마지막으로, 동일한 데이터를 포함하는 새로운 바이트열 객체를 생성하기 위해 메모리 뷰 객체에서 tobytes() 메서드를 호출합니다. 이 바이트 객체는 my_bytes 변수에 저장되고 콘솔에 인쇄됩니다.

참고: memoryview() 함수는 객체를 복사하지 않고 객체의 기본 바이트에 액세스해야 하는 상황에 유용합니다. 그러나 이는 추가 오버헤드가 포함되므로 간단한 문자열을 바이트로 변환하는 데 가장 효율적인 접근 방식이 아닐 수 있습니다.

파이썬3




my_string>=> 'Hello, world!'> #Define a string called my_string with the value 'Hello, world!'.> my_bytes>=> memoryview(my_string.encode(>'utf-8'>)).tobytes()> #Encode the string as bytes using the UTF-8 encoding by calling the encode() method on my_string and passing 'utf-8' as the argument. This will return a bytes object containing the encoded bytes.> #Convert the memoryview object of the bytes object to bytes using the tobytes() method. This creates a new bytes object that is a copy of the original bytes object.> #Print the resulting bytes object using the print() function.#> print>(my_bytes)>

>

Java에서 정수를 문자열로 변환하는 방법

>

산출

b'Hello, world!'>

시간 복잡도: O(n),

공간 복잡도: O(n)

방법 #3: binascii.unhexlify() 방법 사용:

알고리즘 :

자바에서 배열을 정렬하는 방법

1.binascii 모듈 가져오기
2.바이트의 16진수 표현을 포함하는 문자열을 초기화합니다.
3.binascii 모듈의 unhexlify() 메서드를 사용하여 16진수 문자열을 바이트로 변환합니다.
4. 변환된 바이트와 해당 유형을 인쇄합니다.

파이썬3




import> binascii> # initializing string> test_string>=> '4766472069732062657374'> # printing original string> print>(>'The original string : '> +> str>(test_string))> # Using binascii.unhexlify()> # convert string to byte> res>=> binascii.unhexlify(test_string)> # print result> print>(>'The byte converted string is : '> +> str>(res)>+> ', type : '> +> str>(>type>(res)))> #This code is contributed by Jyothi pinjala>

>

>

산출

The original string : 4766472069732062657374 The byte converted string is : b'GfG is best', type :>

시간 복잡도:

binascii.unhexlify() 메서드의 시간 복잡도는 O(n)입니다. 여기서 n은 입력 문자열의 길이입니다.
이 코드의 다른 모든 작업은 O(1)의 시간 복잡도를 갖습니다.
따라서 이 코드의 전체 시간 복잡도는 O(n)입니다.

공간 복잡도:

이 코드의 공간 복잡도는 O(1)입니다. 입력 크기에 관계없이 일정한 양의 추가 공간만 사용하기 때문입니다.

방법 5: struct.pack() 메서드를 사용합니다.

단계별 접근 방식

코드에서 struct 모듈을 가져옵니다.
GFG is best 값으로 'test_string'이라는 문자열을 초기화합니다.
print 문을 사용하여 원래 문자열을 인쇄합니다.
문자열을 바이트로 변환하려면 bytes() 메서드를 사용하세요. 'test_string' 및 'utf-8' 인코딩을 매개변수로 메소드에 전달합니다.
struct.pack() 메서드를 사용하여 바이트를 이진 데이터로 변환합니다. 형식 문자열 '10s'와 바이트를 매개변수로 메서드에 전달합니다. '10s' 형식 문자열은 입력 데이터가 길이 10의 문자열로 처리되어야 함을 나타냅니다.
결과를 'res' 변수에 저장합니다.
print 문을 사용하여 변환된 바이트 문자열을 해당 유형과 함께 인쇄합니다.

파이썬3




import> struct> # initializing string> test_string>=> 'GFG is best'> # printing original string> print>(>'The original string : '> +> str>(test_string))> # Using struct.pack()> # convert string to byte> res>=> struct.pack(>'10s'>, bytes(test_string,>'utf-8'>))> # print result> print>(>'The byte converted string is : '> +> str>(res)>+> ', type : '> +> str>(>type>(res)))>

>

>

안드로이드에서 차단된 번호를 찾는 방법
산출

The original string : GFG is best The byte converted string is : b'GFG is bes', type :>

시간 복잡도: bytes() 및 struct.pack() 메서드의 시간 복잡도는 O(n)입니다. 여기서 n은 입력 문자열의 길이입니다.

보조 공간: bytes() 및 struct.pack() 메서드의 공간 복잡도는 O(n)입니다. 여기서 n은 입력 문자열의 길이입니다.