Python Forum

Full Version: encode text
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
hello programmers.
Please, I have a question about decoding a string that contains pinging. The whole ping is in the listbox, which I need to save as a log to log.txt, but I don't know how to decode this string so that it is not included in \ r and that the output looks like a command line. Thank you
('\r', 'Pinging 8.8.8.8 with 32 bytes of data:\r', 'Reply from 8.8.8.8: bytes=32 time=19ms TTL=53\r', 'Reply from 8.8.8.8: bytes=32 time=17ms TTL=53\r', 'Reply from 8.8.8.8: bytes=32 time=16ms TTL=53\r', 'Reply from 8.8.8.8: bytes=32 time=18ms TTL=53\r', 'Reply from 8.8.8.8: bytes=32 time=22ms TTL=53\r', '\r', 'Ping statistics for 8.8.8.8:\r', '    Packets: Sent = 5, Received = 5, Lost = 0 (0% loss),\r', 'Approximate round trip times in milli-seconds:\r', '    Minimum = 16ms, Maximum = 22ms, Average = 18ms\r')
the object as shown is a tuple, which is immutable, so:
  • convert tuple to list using list(tupplename)
  • iterate through each cell of list, strip off whitespace and replace cell with new value (use enumeration for index, and strip())
  • convert list back to tuple tuple(listname)
Just iterate over the tuple and write to file,then you see that \r magically disappear.
Also look that there is one skip [1:] of first \r ,then you can think of what it dos Think
with open('log.txt', 'w') as f:
    for item in t[1:]:
        f.writelines(item)
Output:
Pinging 8.8.8.8 with 32 bytes of data: Reply from 8.8.8.8: bytes=32 time=19ms TTL=53 Reply from 8.8.8.8: bytes=32 time=17ms TTL=53 Reply from 8.8.8.8: bytes=32 time=16ms TTL=53 Reply from 8.8.8.8: bytes=32 time=18ms TTL=53 Reply from 8.8.8.8: bytes=32 time=22ms TTL=53 Ping statistics for 8.8.8.8: Packets: Sent = 5, Received = 5, Lost = 0 (0% loss), Approximate round trip times in milli-seconds: Minimum = 16ms, Maximum = 22ms, Average = 18ms