473,910 Members | 6,229 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why does the "".join(r) do this?

Hello,

I'm getting an error join-ing strings and wonder if someone can
explain why the function is behaving this way? If I .join in a string
that contains a high character then I get an ascii codec decoding
error. (The code below illustrates.) Why doesn't it just
concatenate?

I'm building up a web page by stuffing an array and then doing
"".join(r) at
the end. I intend to later encode it as 'latin1', so I'd like it to
just concatenate. While I can work around this error, the reason for
it escapes me.

Thanks,
Jim

=============== == program: try.py
#!/usr/bin/python2.3 -u
t="abc"+chr(174 )+"def"
print(u"next: %s :there" % (t.decode('lati n1'),))
print t
r=["x",'y',u'z ']
r.append(t)
k="".join(r)
print k

=============== === command line (on my screen between the first abc
and def is
a circle-R, while between the second two is a black oval with a
white
question mark, in case anyone cares):
jim@joshua:~$ ./try.py
next: abc®def :there
abc�def
Traceback (most recent call last):
File "./try.py", line 7, in ?
k="".join(r)
UnicodeDecodeEr ror: 'ascii' codec can't decode byte 0xae in position
3: ordinal not in range(128)
Jul 18 '05 #1
16 2463
Jim Hefferon wrote:
I'm getting an error join-ing strings and wonder if someone can
explain why the function is behaving this way? If I .join in a string
that contains a high character then I get an ascii codec decoding
error. (The code below illustrates.) Why doesn't it just
concatenate?


It can't just concatenate because your list contains other
items which are unicode strings. Python is attempting to convert
your strings to unicode strings to do the join, and it fails
because your strings contain characters which don't have
meaning to the default decoder.

-Peter
Jul 18 '05 #2

Jim> I'm building up a web page by stuffing an array and then doing
Jim> "".join(r) at the end. I intend to later encode it as 'latin1', so
Jim> I'd like it to just concatenate. While I can work around this
Jim> error, the reason for it escapes me.

Try

u"".join(r)

instead. I think the join operation is trying to convert the Unicode bits
in your list of strings to strings by encoding using the default codec,
which appears to be ASCII.

Skip

Jul 18 '05 #3
Jim Hefferon wrote:
I'm getting an error join-ing strings and wonder if someone can
explain why the function is behaving this way? If I .join in a string
that contains a high character then I get an ascii codec decoding
error. (The code below illustrates.) Why doesn't it just
concatenate?


Let's reduce the problem to its simplest case:
unichr(174) + chr(174) Traceback (most recent call last):
File "<stdin>", line 1, in ?
UnicodeDecodeEr ror: 'ascii' codec can't decode byte 0xae in position 0:
ordinal not in range(128)

So why doesn't it just concatenate? Because there is no way of knowing how
to properly decode chr(174) or any other non-ascii character to unicode:
chr(174).decode ("latin1") u'\xae' chr(174).decode ("latin2") u'\u017d'


Use either unicode or str, but don't mix them. That should keep you out of
trouble.

Peter

Jul 18 '05 #4
Skip Montanaro wrote:
Try

u"".join(r)

instead. I think the join operation is trying to convert the Unicode bits
in your list of strings to strings by encoding using the default codec,
which appears to be ASCII.


This is bound to fail when the first non-ascii str occurs:
u"".join(["a", "b"]) u'ab' u"".join(["a", chr(174)]) Traceback (most recent call last):
File "<stdin>", line 1, in ?
UnicodeDecodeEr ror: 'ascii' codec can't decode byte 0xae in position 0:
ordinal not in range(128)
Apart from that, Python automatically switches to unicode if the list
contains unicode items:
"".join(["a", u"o"])

u'ao'

Peter

Jul 18 '05 #5
Jim Hefferon wrote:
Hello,

I'm getting an error join-ing strings and wonder if someone can
explain why the function is behaving this way? If I .join in a string
that contains a high character then I get an ascii codec decoding
error. (The code below illustrates.) Why doesn't it just
concatenate?

I'm building up a web page by stuffing an array and then doing
"".join(r) at
the end. I intend to later encode it as 'latin1', so I'd like it to
just concatenate. While I can work around this error, the reason for
it escapes me.

Thanks,
Jim

=============== == program: try.py
#!/usr/bin/python2.3 -u
t="abc"+chr(174 )+"def"
print(u"next: %s :there" % (t.decode('lati n1'),))
print t
r=["x",'y',u'z ']
r.append(t)
k="".join(r)
print k

=============== === command line (on my screen between the first abc
and def is
a circle-R, while between the second two is a black oval with a
white
question mark, in case anyone cares):
jim@joshua:~$ ./try.py
next: abc®def :there
abc�def
Traceback (most recent call last):
File "./try.py", line 7, in ?
k="".join(r)
UnicodeDecodeEr ror: 'ascii' codec can't decode byte 0xae in position
3: ordinal not in range(128)


What about unichr() ?
#!/usr/bin/python2.3 -u
t="abc"+unichr( 174)+"def"
print t
print(u"next: %s :there" % (t),)
print t
r=["x",'y',u'z ']
r.append(t)
k="".join(r)
print k



Jul 18 '05 #6
Jim Hefferon wrote:
Hello,

I'm getting an error join-ing strings and wonder if someone can
explain why the function is behaving this way? If I .join in a string
that contains a high character then I get an ascii codec decoding
error. (The code below illustrates.) Why doesn't it just
concatenate?

I'm building up a web page by stuffing an array and then doing
"".join(r) at
the end. I intend to later encode it as 'latin1', so I'd like it to
just concatenate. While I can work around this error, the reason for
it escapes me.

Thanks,
Jim

=============== == program: try.py
#!/usr/bin/python2.3 -u
t="abc"+chr(174 )+"def"
print(u"next: %s :there" % (t.decode('lati n1'),))
print t
r=["x",'y',u'z ']
r.append(t)
k="".join(r)
print k

=============== === command line (on my screen between the first abc
and def is
a circle-R, while between the second two is a black oval with a
white
question mark, in case anyone cares):
jim@joshua:~$ ./try.py
next: abc®def :there
abc�def
Traceback (most recent call last):
File "./try.py", line 7, in ?
k="".join(r)
UnicodeDecodeEr ror: 'ascii' codec can't decode byte 0xae in position
3: ordinal not in range(128)


What about unichr() ?
#!/usr/bin/python2.3 -u
t="abc"+unichr( 174)+"def"
print t
print(u"next: %s :there" % (t),)
print t
r=["x",'y',u'z ']
r.append(t)
# k=u"".join(r)
k="".join(r)
print k
// moma
http://www.futuredesktop.org
Jul 18 '05 #7

Peter> Skip Montanaro wrote:
Try

u"".join(r)

instead. I think the join operation is trying to convert the Unicode bits
in your list of strings to strings by encoding using the default codec,
which appears to be ASCII.


Peter> This is bound to fail when the first non-ascii str occurs:

...

Yeah I realized that later. I missed that he was appending non-ASCII
strings to his list. I thought he was only appending unicode objects and
ASCII strings (in which case what he was trying should have worked). Serves
me right for trying to respond with a head cold.

Skip

Jul 18 '05 #8
Peter Otten wrote:
Skip Montanaro wrote:

Try

u"".join(r)

instead. I think the join operation is trying to convert the Unicode bits
in your list of strings to strings by encoding using the default codec,
which appears to be ASCII.

This is bound to fail when the first non-ascii str occurs:


Is there a way to change the default codec in a part of a program?
(Meaning that different parts of program deal with strings they know are
in a specific different code pages?)
--
C isn't that hard: void (*(*f[])())() defines f as an array of
unspecified size, of pointers to functions that return pointers to
functions that return void.
Jul 18 '05 #9
"Ivan Voras" <ivoras@__geri. cc.fer.hr> wrote in message
news:c8******** **@bagan.srce.h r...
Peter Otten wrote:
Skip Montanaro wrote:

Try

u"".join(r)

instead. I think the join operation is trying to convert the Unicode bitsin your list of strings to strings by encoding using the default codec,
which appears to be ASCII.

This is bound to fail when the first non-ascii str occurs:


Is there a way to change the default codec in a part of a program?
(Meaning that different parts of program deal with strings they know are
in a specific different code pages?)


Does the encoding line (1st or second line of program) do this?
I don't remember if it does or not - although I'd suspect not.
Otherwise it seems like a reasonably straightforward function
to write.

John Roth

--
C isn't that hard: void (*(*f[])())() defines f as an array of
unspecified size, of pointers to functions that return pointers to
functions that return void.

Jul 18 '05 #10

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

Similar topics

14
3054
by: Dave Murray | last post by:
New to Python question, why does this fail? Thanks, Dave ---testcase.py--- import sys, urllib, htmllib def Checkit(URL): try: print "Opening", URL
5
4763
by: Lyn | last post by:
I'm trying to get my head around regular expressions while maintaining some semblance of sanity. I'm canabalising a similar program to construct my own, and it keeps using an expression I'm not familiar with as a pattern matcher. It looks like this: (*) To me, it looks like 0 or more occurences of the beginning of
37
4714
by: Curt | last post by:
If this is the complete program (ie, the address of the const is never taken, only its value used) is it likely the compiler will allocate ram for constantA or constantB? Or simply substitute the values in (as would be required if I used the hideous, evil, much-abused #define :) ----------- const int constantA = 10; static const int constantB = 20;
1
1553
by: James | last post by:
I was told they are included in VB2005 Professional Ed. and not in free Express Ed. I wondered if Standard Ed. has it. Is anyone here using Standard Ed.? Based on Microsoft's Product Feature Comparisons http://msdn.microsoft.com/vstudio/products/compare/ Standard Ed's Deployment Tools is called "ClickOnce", same with the Express Ed. Does this mean "Setup and Deployment projects" are not included?
51
4006
by: Tony Sinclair | last post by:
I'm just learning C#. I'm writing a program (using Visual C# 2005 on WinXP) to combine several files into one (HKSplit is a popular freeware program that does this, but it requires all input and output to be within one directory, and I want to be able to combine files from different directories into another directory of my choice). My program seems to work fine, but I'm wondering about this loop: for (int i = 0; i < numFiles; i++)
16
11312
by: chandanlinster | last post by:
As far as I know floating point variables, that are declared as float follow IEEE format representation (which is 32-bit in size). But chapter1-page no 9 of the book "The C programming language" states that "THE RANGE OF BOTH int AND float DEPENDS ON THE MACHINE YOU ARE USING". Does this mean "float" variables have different sizes on different machines?
4
1130
by: Dachshund Digital | last post by:
Why does Join method call sit there forever? This code works, including the delegate call, but if the join method is ever called, it seems the main thread blocks, and it is hung. HELP! This is driving me nuts! ----------------------------------------------------------------------------------- Imports System Imports System.Threading Imports System.Environment
6
3900
by: Larry Smith | last post by:
Hi there, Can anyone provide any insight on why MSFT introduced "TypeConverter.GetProperties()". There are two classes for dealing with metadata in .NET, 'Type" and "TypeDescriptor". Each has a "GetProperites()" method so why complicate the situation even more than it already is by adding a "GetProperties()" method to "TypeConverter". The class is supposed to be for converting types so "GetProperties()" seems misplaced and redundant (as...
5
2107
by: raylopez99 | last post by:
In C++, you have symbolic overriding of "+", "=", etc, which C# also has. This question is not really about that. Rather, in C#, when you say: MyObject X = new MyObject(); MyObject Y = new MyObject(); X = Y; //what does this '=' mean?
9
550
by: JoeC | last post by:
m_iWidth = (int)pBitmapInfo->bmiHeader.biWidth; m_iHeight = (int)pBitmapInfo->bmiHeader.biHeight; What does this mean? I have seen v=&var->member.thing; but what does it mean when you change the & for int?
0
10037
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
10541
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
9727
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...
1
8099
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7250
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
5939
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...
0
6142
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4337
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3360
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.