How do I get rid of b prefix and ' ' in a string variable
One easy way is to interpolate the bytestrings into another bytestring, do not mix them. Then at the end just decode the bytestring if you want a string:
>>> 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'
So in your example code:
>>> 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'
And since you need a bytestring at the end to write to the telnet session, this way you wouldn't need to re encode your resulting string, use the bytestring as is instead.
How to remove b symbol in python3
The b
symbol indicates that the output of check_process
is a bytes
rather than a str
. The best way to remove it is to convert the output to string before you do any further work on it:
byte_data=subprocess.check_output(["df -k | awk '{print $6}'"],shell=True)
str_data = byte_data.decode('utf-8')
data_arr=str_data.split()
...
The decode
method will take care of any unicode you may have in the string. If your default encoding (or the one used by awk
I suppose) is not UTF-8
, substitute the correct one in the example above.
Possibly an even better way to get around this issue is to tell check_output
to open stdout
as a text stream. The easiest way is to add a universal_newlines=True
argument, which will use the default encoding for your current locale:
str_data = subprocess.check_output(["df -k | awk '{print $6}'"], shell=True, universal_newlines=True)
Alternatively, you can specify an explicit encoding:
str_data = subprocess.check_output(["df -k | awk '{print $6}'"], shell=True, encoding='utf-8')
In both of these cases, you do not need to decode because the output will already be str
rather than bytes
.
Related Topics
Split a Large Json File into Multiple Smaller Files
Retrieve Top N in Each Group of a Dataframe in Pyspark
How to Change the File Name of an Uploaded File in Django
How Would I Make a Dictionary That Can Store User Input in Python
If-Condition With Multiple Actions in Robot Framework
How to Modify the Navigation Toolbar Easily in a Matplotlib Figure Window
Importerror: No Module Named Sklearn (Python)
Valueerror: X and Y Must Be the Same Size
Running Multiple Commands Simultaneously from Python
Pass Variable Between Python Scripts
How to Obtain Second and Fourth Word from Each Line in a File
How to Get the Current Ipython/Jupyter Notebook Name
Converting Numpy Dtypes to Native Python Types
How to Randomly Partition a List into N Nearly Equal Parts
How to Iterate Through a Matrix Column in Python