Javad Karimi
Javad Karimi

Reputation: 23

How convert a string contain unicode characters to UTF in python?

I have a string contains Unicode characters and I want to convert it to UTF-8 in python.

s = '\u0628\u06cc\u0633\u06a9\u0648\u06cc\u062a'

I want convert s to UTF format.

Upvotes: 1

Views: 2206

Answers (2)

GadaaDhaariGeek
GadaaDhaariGeek

Reputation: 1030

Add u as prefix for the string s then encode it in utf-8.

Your code will look like this:

s = u'\u0628\u06cc\u0633\u06a9\u0648\u06cc\u062a'
s_encoded = s.encode('utf-8')
print(s_encoded)

I hope this helps.

Upvotes: 1

Usman
Usman

Reputation: 2029

Add the below line in the top of your .py file.

# -*- coding: utf-8 -*-

It allows you to encode strings directly in your python script, like this:

# -*- coding: utf-8 -*-
s = '\u0628\u06cc\u0633\u06a9\u0648\u06cc\u062a'
print(s)

Output :

بیسکویت 

Upvotes: 0

Related Questions