473,745 Members | 2,137 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

UTF-8 to unicode or latin-1 (and yes, I read the FAQ)

Hi!

I'm struggling with the conversion of a UTF-8 string to latin-1. As far
as I know the way to go is to decode the UTF-8 string to unicode and
then encode it back again to latin-1?

So I tried:

'K\xc3\xb6ni'.d ecode('utf-8') # 'K\xc3\xb6ni' should be 'König',
contains a german 'umlaut'

but failed since python assumes every string to decode to be ASCII?

How can I convert this string to latin-1?

How would you write a function like:

def encode_string(s tring, from_encoding, to_encoding):
#????

Best regards,
Noel

Oct 19 '06 #1
10 2414
No*******@gmx.n et wrote:
I'm struggling with the conversion of a UTF-8 string to latin-1. As far
as I know the way to go is to decode the UTF-8 string to unicode and
then encode it back again to latin-1?

So I tried:

'K\xc3\xb6ni'.d ecode('utf-8') # 'K\xc3\xb6ni' should be 'König',
"Köni", to be precise.
contains a german 'umlaut'

but failed since python assumes every string to decode to be ASCII?
that should work, and it sure works for me:
>>s = 'K\xc3\xb6ni'.d ecode('utf-8')
s
u'K\xf6ni'
>>print s
Köni

what did you do, and how did it fail?

</F>

Oct 19 '06 #2
No*******@gmx.n et wrote:
'K\xc3\xb6ni'.d ecode('utf-8') # 'K\xc3\xb6ni' should be 'König',
contains a german 'umlaut'

but failed since python assumes every string to decode to be ASCII?
No, Python would assume the string to be utf-8 encoded in this case:
>>'K\xc3\xb6ni' .decode('utf-8').encode('lat in1')
'K\xf6ni'

Your code must have failed somewhere else. Try posting actual failing code
and actual traceback.

Oct 19 '06 #3
'K\xc3\xb6ni'.d ecode('utf-8') # 'K\xc3\xb6ni' should be 'König',

"Köni", to be precise.
Äh, yes.
;o)
contains a german 'umlaut'

but failed since python assumes every string to decode to be ASCII?

that should work, and it sure works for me:
>>s = 'K\xc3\xb6ni'.d ecode('utf-8')
>>s
u'K\xf6ni'
>>print s
Köni

what did you do, and how did it fail?
First, thank you so much for answering so fast. I proposed python for a
project and it would be very embarrassing for me if I would fail
converting a UTF-8 string to latin-1.

I realized that my problem ist not the decode to UTF-8. The exception
is raised by print if I try to print the unicode string.

UnicodeEncodeEr ror: 'ascii' codec can't encode character u'\xf6' in
position 1: ordinal not in range(128)

But that is not a problem at all since I can now turn my UTF-8 strings
to unicode! Once again the problem was sitting right in front of my
screen. Silly me...
;o)

Again, thank you for your reply!

Best regards,
Noel

Oct 19 '06 #4
Duncan Booth wrote:
No*******@gmx.n et wrote:
'K\xc3\xb6ni'.d ecode('utf-8') # 'K\xc3\xb6ni' should be 'König',
contains a german 'umlaut'

but failed since python assumes every string to decode to be ASCII?

No, Python would assume the string to be utf-8 encoded in this case:
>'K\xc3\xb6ni'. decode('utf-8').encode('lat in1')
'K\xf6ni'

Your code must have failed somewhere else. Try posting actual failing code
and actual traceback.
You are right. My test code was:

print 'K\xc3\xb6ni'.d ecode('utf-8')

and this line raised a UnicodeDecode exception. I didn't realize that
the exception was actually raised by print and thought it was the
decode. That explains the fact that a 'ignore' in the decode showed no
effect at all, too.

Thank you for helping!

Best regards,
Noel

Oct 19 '06 #5
No*******@gmx.n et wrote:
>
print 'K\xc3\xb6ni'.d ecode('utf-8')

and this line raised a UnicodeDecode exception.
Works for me.

Note that 'K\xc3\xb6ni'.d ecode('utf-8') returns a Unicode object. With
print this is implicitly converted to string. The char set used depends
on your console

Check this out for understanding it:
>>u = 'K\xc3\xb6ni'.d ecode('utf-8')
s=u.encode('i so-8859-1')
u
u'K\xf6ni'
>>s
'K\xf6ni'
>>>
Ciao, Michael.
Oct 19 '06 #6
Michael Ströder wrote:
No*******@gmx.n et wrote:

print 'K\xc3\xb6ni'.d ecode('utf-8')

and this line raised a UnicodeDecode exception.

Works for me.

Note that 'K\xc3\xb6ni'.d ecode('utf-8') returns a Unicode object. With
print this is implicitly converted to string. The char set used depends
on your console
And that was the problem. I'm developing with eclipse (PyDev). The
console is integrated in the development environment. As I print out an
unicode string python tries to encode it to ASCII. And since the string
contains non ASCII characters it fails. That is no problem if you are
aware of this.

My mistake was that I thought the exception was raised by my call to
decode('UTF-8') because print and decode were on the same line and I
thought print could never raise an exception. Seems like I've learned
something today.

Best regards,
Noel

Oct 19 '06 #7
On 2006-10-19, Michael Ströder <mi*****@stroed er.comwrote:
No*******@gmx.n et wrote:
>>
print 'K\xc3\xb6ni'.d ecode('utf-8')

and this line raised a UnicodeDecode exception.

Works for me.

Note that 'K\xc3\xb6ni'.d ecode('utf-8') returns a Unicode
object. With print this is implicitly converted to string. The
char set used depends on your console
No, the setting of the console encoding (sys.stdout.enc oding) is
ignored. It's a good thing, too, since it's pretty flaky. It uses
sys.getdefaulte ncoding(), which is always 'ascii' as far as I
know.
--
Neil Cerutti
Oct 19 '06 #8
In <sl************ *******@FIAD06. norwich.edu>, Neil Cerutti wrote:
>Note that 'K\xc3\xb6ni'.d ecode('utf-8') returns a Unicode
object. With print this is implicitly converted to string. The
char set used depends on your console

No, the setting of the console encoding (sys.stdout.enc oding) is
ignored.
Nope, it is not ignored. This would not work then::

In [2]: print 'K\xc3\xb6nig'. decode('utf-8')
König

In [3]: import sys

In [4]: sys.getdefaulte ncoding()
Out[4]: 'ascii'
Ciao,
Marc 'BlackJack' Rintsch
Oct 19 '06 #9
On 2006-10-19, Marc 'BlackJack' Rintsch <bj****@gmx.net wrote:
In <sl************ *******@FIAD06. norwich.edu>, Neil Cerutti wrote:
>>Note that 'K\xc3\xb6ni'.d ecode('utf-8') returns a Unicode
object. With print this is implicitly converted to string. The
char set used depends on your console

No, the setting of the console encoding (sys.stdout.enc oding) is
ignored.

Nope, it is not ignored. This would not work then::

In [2]: print 'K\xc3\xb6nig'. decode('utf-8')
König

In [3]: import sys

In [4]: sys.getdefaulte ncoding()
Out[4]: 'ascii'
Interesting! Thanks for the correction.

--
Neil Cerutti
This scene has a lot of activity. It is busy like a bee dive.
--Michael Curtis
Oct 19 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
14060
by: Aleksandar Matijaca | last post by:
Hi there, I am in some need of help. I am trying to parse using the apache sax parser a file that has vaid UTF-8 characters - I keep end up getting a sun.io.MalformedInputException error. This is my code:
38
5739
by: Haines Brown | last post by:
I'm having trouble finding the character entity for the French abbreviation for "number" (capital N followed by a small supercript o, period). My references are not listing it. Where would I find an answer to this question (don't find it in the W3C_char_entities document). -- Haines Brown brownh@hartford-hwp.com
76
15146
by: Zenobia | last post by:
How do I display character 151 (long hyphen) in XHTML (utf-8) ? Is there another character that will substitute? The W3C validation parser, http://validator.w3.org, tells me that this character and the ones around it are illegal - then, after resubmission it flags no errors. So, are there any illegal characters between 0 and 255 in the UTF-8 character set or is it just my imagination that the W3C validation parser thinks there are -...
48
4637
by: Zenobia | last post by:
Recently I was editing a document in GoLive 6. I like GoLive because it has some nice features such as: * rewrite source code * check syntax * global search & replace (through several files at once) * regular expression search & replace. Normally my documents are encoded with the ISO setting. Recently I was writing an XHTML document. After changing the encoding to UTF-8 I used the
16
6168
by: lawrence | last post by:
I was told in another newsgroup (about XML, I was wondering how to control user input) that most modern browsers empower the designer to cast the user created input to a particular character encoding. This arose in answer to my question about how to control user input. I had complained that I had users who wrote articles in Microsoft Word or WordPerfect and then input that to the web through a textarea box on a form I'd created. I've...
1
6160
by: JJBW | last post by:
Hi I am creating some aspx files in Visual Studio 2003 for a Danish web site. The page is encoded as UTF-8 - However, when I save the the aspx file as "UTF-8 without signature" the Danish characters Å Æ Ø are not displayed correctly, when I choose to save the file as "UTF-8 with signature" the characters are displayed correctly.
11
2010
by: Jean-François Michaud | last post by:
Hello all, I'm having a little problem, The UTF-8 parser we are using converts the newline entity ( ) within an attribute that we are using to paliate CSS limitations. After the parser has gone through the document, the entity is converted to \n, which then effectively tosses out the window the behavior we are getting by keepinig the entity AS IS within the document.
4
1561
by: Steve | last post by:
I wish my aspx pages to be interpreted as UTF-8 by browsers. Apart from setting the following in the web.config file: <globalization fileEncoding="utf-8" requestEncoding="utf-8" responseEncoding="utf-8" /> 1. Do I also have to specify <meta http-equiv="Content-Type" content="text/html; charset=utf-8"in every aspx page?
3
2787
by: majna | last post by:
I have character counter for textarea wich counting the characters. Special character needs same place as two normal characters because of 16-bit encoding. Counter is counting -2 when special character is added like some language specific char. How to count specials like 1 char? tnx
2
10170
by: MichaelSchoeler | last post by:
Hi, I'm having problems with the WebClient class regarding UTF-8 encoded data. When I access a specific webservice directly I can see the data arrives in corretly formatted UTF-8. But when I try to pull data from the same webservice url through the WebClient class I get partly garbled UTF-8 data in return. Only some UTF-8 chars (double byte pairs) seems to be corrupted. // Does not work WebClient wc = new WebClient(); string...
0
8970
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8795
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9486
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9214
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8219
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6057
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4573
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
2759
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2195
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.