SORU
3 Mart 2009, Salı


Python bir dize bayt dönüştürmek

Bu kod, harici bir program standart çıktı almak için kullanıyorum:

>>> from subprocess import *
>>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0]

() İletişim yöntemi bir bayt dizisi döndürür:

>>> command_stdout
b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file2\n'

Ancak, çıktı ile çalışmak için normal bir Python string olarak istiyorum. Ben böyle baskı:

>>> print(command_stdout)
-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file1
-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file2

binascii.b2a_qp() yöntemi için var sanıyordum, ama ben denedim, aynı bayt dizisi daha var:

>>> binascii.b2a_qp(command_stdout)
b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file2\n'

Kimseye bayt değerinin dize geri dönüştürmek nasıl biliyor mu? , ""Elle yapmak yerine. pilleri kullanarak yani Ve Python 3 ile idare etmek istiyorum.

CEVAP
3 Mart 2009, Salı


Bayt dize üretmek için nesne deşifre etmek gerekir:

>>> b"abcde"
b'abcde'

# utf-8 is used here because it is a very common encoding, but you
# need to use the encoding your data is actually in.
>>> b"abcde".decode("utf-8") 
'abcde'

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • Call Me Howard

    Call Me Howa

    18 AĞUSTOS 2012
  • Doc Adams

    Doc Adams

    20 HAZİRAN 2007
  • xSammyJoe1

    xSammyJoe1

    19 Temmuz 2011