【问题标题】:(Python) How can i convert byte string into a raw string with double quote as(Python)如何将字节字符串转换为带有双引号的原始字符串
【发布时间】:2020-02-03 17:01:56
【问题描述】:

我将这个字节表示为字符串:

b'google-site-verification=pFgmIQ6qK3YjcRAAhsKiPzmEiOVcynQslFMEba5lXvs'

我想将其转换为如下所示的原始字符串:

r'"google-site-verification=pFgmIQ6qK3YjcRAAhsKiPzmEiOVcynQslFMEba5lXvs"

(打印时不显示 r')

我用 replace 尝试过,但不知道如何让它工作。 也许有人可以在这里帮助我。

问候

编辑完整代码:

def decode_txt_rdata(rdata, rdlen):
    """decode TXT RR rdata into a string of quoted text strings,
    escaping any embedded double quotes"""
    txtstrings = []
    position = 0
    while position < rdlen:
        slen, = struct.unpack('B', rdata[position:position+1])
        s = rdata[position+1:position+1+slen]
        s = '"{}"'.format(s.replace(b'"', b'"').decode())
        txtstrings.append(s)
        position += 1 + slen
    return ' '.join(txtstrings)

【问题讨论】:

  • 我想如果你有一个额外的单引号,即r'"应该是r"。无论如何,您都可以使用 decode 功能,如b'google-site-verification=pFgmIQ6qK3YjcRAAhsKiPzmEiOVcynQslFMEba5lXvs'.decode("utf-8") 中所述here
  • 我使用s = '"{}"'.format(s.replace(b'"', b'"').decode()) 转换为字符串,但它不会忽略\010 之类的反斜杠字符并将它们作为转义字符。当我使用 decode('unicode-escape') 时,原始字节字符串也会在反斜杠字符处发生变化。我不知道该怎么办...
  • r'"google-site-verification=pFgmIQ6qK3YjcRAAhsKiPzmEiOVcynQslFMEba5lXvs" 似乎不是一个有效的字符串。
  • 你试过b'google-site-verification=pFgmIQ6qK3YjcRAAhsKiPzmEiOVcynQslFMEba5lXvs'.decode(("utf-8")吗?如果是这样,结果是否与您想要的不同?
  • 它告诉我'str' object has no attribute 'decode',当我在转换为字符串之前使用它时,我得到:google-site-verification=Y3dKKFu_H3cJ3l66OBt0QIUL3 Z6cXR0UxhulSdc28lY 仍然带有换行符..

标签: python escaping character


【解决方案1】:

从第一个答案中使用

Convert Bytes to String

假设

希望是:

r"google-site-verification=pFgmIQ6qK3YjcRAAhsKiPzmEiOVcynQslFMEba5lXvs"

NOT(无效):

r'"google-site-verification=pFgmIQ6qK3YjcRAAhsKiPzmEiOVcynQslFMEba5lXvs"

# Byte String
s = b'google-site-verification=pFgmIQ6qK3YjcRAAhsKiPzmEiOVcynQslFMEba5lXvs'

# String
decode_s = s.decode('utf-8')

print(f"Byte string\n\t{s}\n\n")
print(f"Decoded Byte string\n\t{decode_s}\n")
print(f'Is decoded == Desired \n{decode_s==r"google-site-verification=pFgmIQ6qK3YjcRAAhsKiPzmEiOVcynQslFMEba5lXvs"}' )

输出

Byte string    
    b'google-site-verification=pFgmIQ6qK3YjcRAAhsKiPzmEiOVcynQslFMEba5lXvs'

Decoded Byte string    
    google-site-verification=pFgmIQ6qK3YjcRAAhsKiPzmEiOVcynQslFMEba5lXvs

Is decoded == Desired
    True

【讨论】:

    猜你喜欢
    • 2015-10-27
    • 1970-01-01
    • 2017-08-21
    • 2013-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-29
    • 1970-01-01
    相关资源
    最近更新 更多