如何摆脱字符串变量中的b前缀和''

时间:2019-07-26 21:01:00

标签: python-3.x

因此,我试图获取一段代码以在基于函数的两个变量之间运行重播,它获取了正确的变量,但是当我发送最终命令时,它会发送带有b和''的内容telnet命令

import telnetlib

host = "192.168.1.13" #changes for each device
port = 9993 #specific for hyperdecks
timeout = 10

session = telnetlib.Telnet(host, port, timeout)

TCi = 1
TCo = 1
def In():
    global TCi
    session.write(b"transport info \n")
    by = session.read_until(b";00",.5)
    print(by)
    s = by.find(b"00:")
    TCi = by[s:s+11]
def Out():
    global TCo
    session.write(b"transport info \n")
    by = session.read_until(b";00",.5)
    print(by)
    s = by.find(b"00:")
    TCo = by[s:s+11]
def IOplay():
    IOtc = "playrange set: in: " + str(TCi) + " out: " + str(TCo) + " \n"
    print(IOtc.encode() )
    session.write(IOtc.encode() )
    speed = "play: speed: 2 \n"
    session.write(speed.encode() )

预期

b"playrange set: in: 00:00:01;11 out: 00:00:03;10 \n"

已收到

b"playrange set: in: b'00:00:01;11' out: b'00:00:03;10' \n"

我需要删除字符串的前缀

2 个答案:

答案 0 :(得分:0)

在打印时,您可以将其解码为utf-8字符串:

print(IOtc.encode().decode("utf-8"))

答案 1 :(得分:0)

一种简单的方法是将字节串内插到另一个字节串中,不要混合它们。然后最后,如果需要一个字符串,只需解码该字节字符串:

>>> no = "Interpolate string and %s" % b
>>> no
"Interpolate string and b'bytes'"

>>> yes = b"Interpolate bytes and %s" % b
>>> yes
b'Interpolate bytes and bytes'

>>> yes.decode()
'Interpolate bytes and bytes'

在您的示例代码中:

>>> TCi = b"1"
>>> TCo = b"2"
>>> IOtc = b"playrange set: in: %s out: %s\n" % (TCi, TCo)
>>> IOtc
b'playrange set: in: 1 out: 2\n'

并且由于您最后需要一个字节字符串来写入telnet会话,因此您无需重新编码生成的字符串,请照原样使用该字节字符串。