user3661564
user3661564

Reputation: 107

How to remove b symbol in python3

How to remove b symbol from python3 script?

import subprocess

get_data=subprocess.check_output(["df -k | awk '{print $6}'"],shell=True)
data_arr=get_data.split()
data_arr.pop(0)
data_arr.pop(0)
for i in data_arr[:]:
    print(str(i))

Output

b'/dev/shm'
b'/run'
b'/sys/fs/cgroup'
b'/'
b'/tmp'
b'/test'
b'/boot'
b'/home'
b'/var'
b'/mnt/install'
b'/mnt/snapshot'
b'/mnt/share'
b'/mnt/storage'
b'/mnt/linux'
b'/mnt/download'
b'/run/user/1001'

Upvotes: 7

Views: 13558

Answers (4)

Philippe Sisowath
Philippe Sisowath

Reputation: 2918

You can provide to encoding parameter to check_ouptut to remove all the b (byte format)

for example:

import subprocess

get_data=subprocess.check_output(["df -k | awk '{print $6}'"],shell=True, encoding='utf-8')
data_arr=get_data.split()
data_arr.pop(0)
data_arr.pop(0)
for i in data_arr[:]:
    print(str(i))

Encoding paramater for check_output() is available from Python 3.6

Upvotes: 0

Anto
Anto

Reputation: 3896

from my SO question:

read_key = ["binary", "arg1", "arg2", "arg3"]
proc = subprocess.Popen(read_key, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf-8')
output = proc.communicate()[0]
print(output)
MY_EXPECTED_OUTPUT_STRING

Upvotes: 0

shailu
shailu

Reputation: 330

try this: a=str(yourvalue,'utf-8')

Upvotes: -2

Mad Physicist
Mad Physicist

Reputation: 114230

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.

Upvotes: 13

Related Questions