0

I am new and I'm trying to insert a character before a string.

If I have a string like so:

'wB0JSYuEUshUkgpKi8TRTwv/EABgBAQADAQAAAAAAA'

I want to add b before the string but not part of the string-like so:

b'wB0JSYuEUshUkgpKi8TRTwv/EABgBAQADAQAAAAAAA'

Here's what I tried:

test = 'b' + words[1]
test

but this obviously returns the b within the string, which is not what I want.

martineau
  • 119,623
  • 25
  • 170
  • 301
Dom
  • 43
  • 6
  • 1
    What's the use case? The `b` isn't part of the string itself, but a marker for a *literal* of type `bytes`. If you just need a `bytes` value, use `test = words.encode()`. – chepner Apr 27 '20 at 14:50

3 Answers3

5

That b is not part of the string, it's a special syntax in Python 3.x to indicate that it's a bytes literal (see this post). If you want to convert a "normal" string into a bytes literal, do this:

st = 'abc'
bl = st.encode()

bl
=> b'abc'
Óscar López
  • 232,561
  • 37
  • 312
  • 386
0

I'm not exactly sure what you mean. But assuming words is a list of strings, and index 1 = 'wB0JSYuEUshUkgpKi8TRTwv/EABgBAQADAQAAAAAAA' you could print(f'b {words[1]}')

Oliver Robie
  • 818
  • 2
  • 11
  • 30
0

There is a bit of confusion here. In python "" is a string and b"" is a byte string. These are completely different objects. They can be converted to one another, but they are not the same thing. You can't add "b to a string". Essentially a byte string b"" is a string of the bytes that generate a string, and a string is well the string. For example,

x = 'STRING'   #The string itself. 
y = x.encode() #The bytes for the string. Note that ascii bytes are written in ascii. 

a = 'MyName®'  #The string itself.
b = a.encode() #The bytes for the string. The last character takes two non-ascii bytes. 
c = b.decode() #Covert the bytes back to a string. 
Bobby Ocean
  • 3,120
  • 1
  • 8
  • 15