Learn Python string using simple stepby step examples.

Example 1: Encode and Decode string

This example will teach you the following:

  1. How to print strings
  2. How utf-8 encode and decode stringsin python.

Step 1: Create Project

Create python project or file named main.py.

Step 2: Write Code

Here’s how you encode a string to utf-8 using the encode() function:

b = s.encode('utf-8')

and here’s how you decode using the decode() function:

print(b.decode('utf-8'))

Add the following code:

s = 'Hello People'
print(s)
b = s.encode('utf-8')
print(b)
print(b.decode('utf-8'))

Step 3: Run

Run the code by navigating to the project directory:

cd your_project_folder

Then execute:

python main.py

You will get the following:

Hello People
b'Hello People'
Hello People

Categorized in: