0

I want to encode the string "tamilnadu" and the output is like "dGFtaWxuYWR1"

str = "tamilnadu";
print str.encode('base64','strict') //dGFtaWxuYWR1

But when I am encode the string its shows an error like this

'base64' is not a text encoding; use codecs.encode() to handle arbitrary codecs

I tired all the encoding techniques, but the output for the sting is not like this encode value "dGFtaWxuYWR1"

How can I encode the string in python 3.4

eyllanesc
  • 235,170
  • 19
  • 170
  • 241

3 Answers3

3

You need base64 module

import base64
base64.b64encode(bytes('tamilnadu', 'utf-8'))

Also, don't use str as a variable name - its a keyword in python which represents string type.

Nishant
  • 409
  • 6
  • 16
  • I tired already, its working when I encode the string the encode sting should like this "dGFtaWxuYWR1" .While using this method the output like this "b'dGFtaWxuYWR1'" –  Jan 10 '19 at 23:52
  • @Rajendranbala It's essentially the same. The `b` at the front means it's a byte literal instead of a string type. See [What does the 'b' character do in front of a string literal?](https://stackoverflow.com/q/6269765/2745495). – Gino Mempin Jan 11 '19 at 00:10
  • 1
    @Coder It's funny how this solution did not work, but the accepted answer with an identical solution (but with broken code) posted 40 minutes after this one did. – cs95 Jan 11 '19 at 00:48
-1

Use base64 library

    import base64
    c="tamilnadu"
    c=base64.b64encode(bytes(c, 'utf-8')) // b'dGFtaWxuYWR1'
    c1=base64.b64decode(c) 
    c=str(c).replace("'","")  // bdGFtaWxuYWR1
    print("Encode",c[1:])       // dGFtaWxuYWR1 
    c1=str(c1).replace("'","") // b'tamilnadu'
    print("Decode=",c1[:1]) // tamilnadu

After encode you have replace the ' and first character b

Balaji Rajendran
  • 357
  • 5
  • 17
-3

You need base64 module

import base64
base64.b64encode(bytes('tamilnadu', 'utf-8'))

Also, don't use str as a variable name - its a keyword in python which represents string type.