Python strip() function malfunction

Asked

Viewed 181 times

0

I have a list in a file, where each line has a user agent (with " at the beginning and end of each line), which is used in a later part of a program, to perform automated tests using Selenium. When opening the list, I implemented that at each line read I would take the first and last character of each line as follows:

USER_AGENTS_FILE = './users.txt'
RUNNING = True
    def LoadUserAgents(uafile=USER_AGENTS_FILE):
    uas = [ ]
    with open(uafile, 'rb' ) as uaf:
        for ua in uaf.readlines():
            if ua:
                uas.append(ua.strip()[1:-1-1])
    random.shuffle(uas)
    return uas 
uas = LoadUserAgents()

Adding also the functionality of randomly choosing lines. However, when I try to display the list by the following command:

for i in range(0,10):
print(random.choice(uas))

I get something like this:

 b'Mozilla/5.0 (BeOS; U; BeOS BePC; en-US; rv:1.8.1.6) Gecko/20070731 BonEcho/2.0.0.'

When in fact, you’d need to get:

Mozilla/5.0 (BeOS; U; BeOS BePC; en-US; rv:1.8.1.6) Gecko/20070731 BonEcho/2.0.0.

someone could help me solve this problem?

1 answer

0


Its string is in byte format, and only needs to be decoded to a standard format.

>>> s =  b'Mozilla/5.0 (BeOS; U; BeOS BePC; en-US; rv:1.8.1.6) Gecko/20070731 BonEcho/2.0.0.'
>>> s.decode("utf-8")
'Mozilla/5.0 (BeOS; U; BeOS BePC; en-US; rv:1.8.1.6) Gecko/20070731 BonEcho/2.0.0.'
  • It worked perfectly! / Thanks for the help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.