473,545 Members | 1,471 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

printing unicode strings

Can anyone tell me why I can print out the individual variables in the
following code, but when I print them out combined into a single
string, I get an error?

symbol = u'ibm'
price = u'4 \xbd' # 4 1/2

print "%s" % symbol
print "%s" % price.encode("u tf-8")
print "%s %s" % (symbol, price.encode("u tf-8") )

--output:--
ibm
4 1/2
File "pythontest.py" , line 6, in ?
print "%s %s" % (symbol, price.encode("u tf-8") )
UnicodeDecodeEr ror: 'ascii' codec can't decode byte 0xc2 in position
2: ordinal not in range(128)

Jul 24 '07 #1
3 2216
7stud wrote:
Can anyone tell me why I can print out the individual variables in the
following code, but when I print them out combined into a single
string, I get an error?

symbol = u'ibm'
price = u'4 \xbd' # 4 1/2

print "%s" % symbol
print "%s" % price.encode("u tf-8")
print "%s %s" % (symbol, price.encode("u tf-8") )

--output:--
ibm
4 1/2
File "pythontest.py" , line 6, in ?
print "%s %s" % (symbol, price.encode("u tf-8") )
UnicodeDecodeEr ror: 'ascii' codec can't decode byte 0xc2 in position
2: ordinal not in range(128)
For format % args, if the format or any arg is a unicode string, the result
will be unicode, too. This implies that byte strings have to be decoded,
and for that process the default ascii codec is used. In your example
print "%s %s" % (symbol, price.encode("u tf-8") )
symbol is a unicode, so python tries to decode "%s %s" and "4 \xc2\xbd"
(the result of price.encode("u tf8")). The latter contains non-ascii chars
and fails.

Solution: use unicode throughout and let the print statement do the
encoding.
>>symbol = u"ibm"
price = u"4 \xbd"
print u"%s %s" % (symbol, price)
ibm 4 ?

Sometimes, e. g. if you redirect stdout, the above can fail. Here's a
workaround that uses utf8 in such cases.

import sys
if sys.stdout.enco ding is None:
import codecs
sys.stdout = codecs.lookup(" utf8").streamwr iter(sys.stdout )

Peter

Jul 24 '07 #2
On Jul 25, 6:56 am, 7stud <bbxx789_0...@y ahoo.comwrote:
Can anyone tell me why I can print out the individual variables in the
following code, but when I print them out combined into a single
string, I get an error?

symbol = u'ibm'
price = u'4 \xbd' # 4 1/2

print "%s" % symbol
print "%s" % price.encode("u tf-8")
print "%s %s" % (symbol, price.encode("u tf-8") )

--output:--
ibm
4 1/2
File "pythontest.py" , line 6, in ?
print "%s %s" % (symbol, price.encode("u tf-8") )
UnicodeDecodeEr ror: 'ascii' codec can't decode byte 0xc2 in position
2: ordinal not in range(128)
Because the first part is Unicode and the second part (after encoding
in utf8) is str.

It is trying to convert the second part to Unicode, using the default
codec (ascii), which of course must fail:
>>price = u"4 \xbd"
price.encode( "utf8")
'4 \xc2\xbd'
>>>>>price.enco de("utf8").deco de("ascii")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeEr ror: 'ascii' codec can't decode byte 0xc2 in position
2: ordinal
not in range(128)
>>>

Jul 24 '07 #3
Thanks.

Jul 25 '07 #4

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

Similar topics

4
6855
by: Pekka Niiranen | last post by:
Hi, I have a multiuser script, that I would like to convert to Python. The users open simultaneous telnet -sessions from win2000 to an unix machine and possibly edit unicode textfiles. Currently users use vi and more, but I would like to add unicode support to the script. I would not like to force them to open X-sessions in order to show...
11
4332
by: Marian Aldenhövel | last post by:
Hi, I am very new to Python and have run into the following problem. If I do something like dir = os.listdir(somepath) for d in dir: print d The program fails for filenames that contain non-ascii characters.
2
1531
by: Fuzzyman | last post by:
How does the print statement decode unicode strings itis passed ? (By that I mean which encoding does it use). Under windows it doesn't appear to use defaultencoding. On my system the default encoding is ascii, yet the terminal encoding is latin1 (or cp1252 or whatever, but not ascii). This means that print '£' works fine, yet unicode('£')...
4
6046
by: webdev | last post by:
lo all, some of the questions i'll ask below have most certainly been discussed already, i just hope someone's kind enough to answer them again to help me out.. so i started a python 2.3 script that grabs some web pages from the web, regex parse the data and stores it localy to xml file for further use.. at first i had no problem using...
2
2613
by: Neil Schemenauer | last post by:
python-dev@python.org.] The PEP has been rewritten based on a suggestion by Guido to change str() rather than adding a new built-in function. Based on my testing, I believe the idea is feasible. It would be helpful if people could test the patched Python with their own applications and report any incompatibilities. PEP: 349
29
3491
by: Ron Garret | last post by:
>>> u'\xbd' u'\xbd' >>> print _ Traceback (most recent call last): File "<stdin>", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode character u'\xbd' in position 0: ordinal not in range(128) >>>
1
7274
by: sheldon.regular | last post by:
I am new to unicode so please bear with my stupidity. I am doing the following in a Python IDE called Wing with Python 23. äöü äöü '\xc3\xa4\xc3\xb6\xc3\xbc' u'\xe4\xf6\xfc' u'\xe4\xf6\xfc' äöü
5
6901
by: Xah Lee | last post by:
If i have a nested list, where the atoms are unicode strings, e.g. # -*- coding: utf-8 -*- ttt=, ,...] print ttt how can i print it without getting the u'\u1234' notation? i.e. i want it print just like this: , ...] I can of course write a loop then for each string use
2
1589
by: David | last post by:
Hi list. I've never used unicode in a Python script before, but I need to now. I'm not sure where to start. I'm hoping that a kind soul can help me out here. My current (almost non-existant) knowledge of unicode: string types. What I don't understand yet is what encodings are and when you'd want/need to use them. What I'd like is to...
0
7465
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...
0
7805
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7416
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7752
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...
1
5325
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3449
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...
0
3441
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1878
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
701
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...

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.