473,659 Members | 2,996 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why " ".some_stri ng is often used ?


Hi all,

This is not the first time I see this way of coding in Python and
I wonder why this is coded this way:

Howto on PyXML
(http://pyxml.sourceforge.net/topics/howto/node14.html)
shows it on this function, but I saw that in many other pieces of code:

def normalize_white space(text):
"Remove redundant whitespace from a string"
return ' '.join(text.spl it())

Is there a reason to do instead of just returning join(text.split ()) ?
why concatenate " " to the string and not just returning the string instead ?

Thanks in advance for your explanations.

Regards,

--
Stephane Ninin

Jul 18 '05 #1
12 1530
"Stéphane Ninin" wrote:
Is there a reason to do instead of just returning join(text.split ()) ?
why concatenate " " to the string and not just returning the string
instead ?


Because they're not the same thing unless you've already done

from string import join

first. join is not a builtin function.

--
__ Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
/ \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
\__/ I get my kicks above the wasteline, sunshine
-- The American, _Chess_
Jul 18 '05 #2
Also sprach Erik Max Francis :
Is there a reason to do instead of just returning join(text.split ()) ?
why concatenate " " to the string and not just returning the string
instead ?


Because they're not the same thing unless you've already done

from string import join

first. join is not a builtin function.


Ok. Thanks.
I just realized that "." had also nothing to do with concatenation here.
Jul 18 '05 #3
On 2004-01-07, Erik Max Francis <ma*@alcyone.co m> wrote:
Because they're not the same thing unless you've already done

from string import join

first. join is not a builtin function.


You know, given the volumes of text Pythonistas write about Python not
falling to the Perlish trap of magic linenoise this certainly smacks of it,
don'tcha think? Wonder how this idiom slipped in. To think all this time I
have been doing:

import string
string.join()

--
Steve C. Lamb | I'm your priest, I'm your shrink, I'm your
PGP Key: 8B6E99C5 | main connection to the switchboard of souls.
-------------------------------+---------------------------------------------
Jul 18 '05 #4
"Stéphane Ninin" <st************ @yahoo.fr> wrote in message
news:Xn******** *************** ***********@213 .228.0.4...

Hi all,

This is not the first time I see this way of coding in Python and
I wonder why this is coded this way:

Howto on PyXML
(http://pyxml.sourceforge.net/topics/howto/node14.html)
shows it on this function, but I saw that in many other pieces of code:

def normalize_white space(text):
"Remove redundant whitespace from a string"
return ' '.join(text.spl it())

Is there a reason to do instead of just returning join(text.split ()) ?
why concatenate " " to the string and not just returning the string instead ?

This particular idiom replaces sequences of multiple whitespace
charaters with a single blank.

And I agree, it's not entirely obvious why it's a string
method rather than a list method, since it operates on
a list, not on a string. The only explanation that makes
sense is that, as a list method, it would fail if the list
contained something other than a string. That's still
not very friendly, though.

John Roth
Thanks in advance for your explanations.

Regards,

--
Stephane Ninin

Jul 18 '05 #5
John Roth wrote:
And I agree, it's not entirely obvious why it's a string
method rather than a list method, since it operates on
a list, not on a string. The only explanation that makes
sense is that, as a list method, it would fail if the list
contained something other than a string. That's still
not very friendly, though.


On the contrary, I think that's the best reason. Lists have nothing to
do with strings, and so very string-specific methods (discounting
system-wide things such as str or repr) being included in lists is not
the right approach. Furthermore, the methods associated with a list
tend to become the "pattern" that sequence types must fulfill, and it
sets a terribly bad precedent to attach whatever domain-specific
application that's needed into a sequence type just because it's easiest
on the eyes at the moment.

The .join method is inherently string specific, and belongs on strings,
not lists. There's no doubting that seeing S.join(...) for the first
time is a bit of a surprise, but once you understand the reasoning
behind it, it makes perfect sense and makes it clear just how much it
deserves to stay that way.

And above all, of course, if you think it personally looks ugly, you can

from string import join

or write your own join function that operates over sequences and does
whatever else you might wish. That's what the flexibility is there for.

--
__ Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
/ \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
\__/ Life is not a spectacle or a feast; it is a predicament.
-- George Santayana
Jul 18 '05 #6
John Roth wrote:

And I agree, it's not entirely obvious why it's a string
method rather than a list method, since it operates on
a list, not on a string. The only explanation that makes
sense is that, as a list method, it would fail if the list
contained something other than a string. That's still
not very friendly, though.


One could about as easily argue (and I believe several have done
this quite well in the past, better than I anyway) that you are
actually operating on the *string*, not the list. You are in
effect asking the string to act as a joiner for the elements in the
list, not asking the list to join itself using the specified
string.

At least, if you look at it that way, it might be easier to swallow.

-Peter
Jul 18 '05 #7
Peter Hansen <pe***@engcorp. com> writes:
John Roth wrote:

And I agree, it's not entirely obvious why it's a string
method rather than a list method, since it operates on
a list, not on a string. The only explanation that makes
sense is that, as a list method, it would fail if the list
contained something other than a string. That's still
not very friendly, though.


One could about as easily argue (and I believe several have done
this quite well in the past, better than I anyway) that you are
actually operating on the *string*, not the list. You are in
effect asking the string to act as a joiner for the elements in the
list, not asking the list to join itself using the specified
string.

At least, if you look at it that way, it might be easier to swallow.


Can't we have both. This is called a reversing method (Beck, Smalltalk
Best Practice Patterns) because it allows you to send several messages
to the same object instead of switching between different instances,
allowing the code to be more regular.

class MyList(list):
def join(self, aString):
return aString.join(se lf)
Like this:

lst = ['one', 'two', 'three']
print lst
print lst.join('\n')

I'd also like a reversing method for len

class MyList(list):
def len(self):
return len(self)

Often when I program against an instance I intuitively start each line
of code by writing the variable name and then a dot and then the
operation. The lack of a reversing method for len and join means that
my concentration is broken a tiny fraction of a second when I have to
remember to use another object or the global scope to find the
operation that I am after. Not a showstopper by any definition, but
irritating nonetheless.

--

Syver Enstad
Jul 18 '05 #8
On Thu, 08 Jan 2004 03:50:04 -0800, rumours say that Erik Max Francis
<ma*@alcyone.co m> might have written:

[' '.join discussion]
And above all, of course, if you think it personally looks ugly, you can

from string import join

or write your own join function that operates over sequences and does
whatever else you might wish. That's what the flexibility is there for.


I believe str.join(string , sequence) works best for the functional types
(no need to rely on the string module).
--
TZOTZIOY, I speak England very best,
Ils sont fous ces Redmontains! --Harddix
Jul 18 '05 #9
On 08 Jan 2004 16:34:39 +0100, rumours say that Syver Enstad
<sy************ *@online.no> might have written:
I'd also like a reversing method for len

class MyList(list):
def len(self):
return len(self)


You can always use the __len__ attribute in this specific case.

And now for the hack value:

class MyList(list):
import new as _new, __builtin__
def __getattr__(sel f, attr):
try:
return self._new.insta ncemethod( \
getattr(self.__ builtin__, attr), \
self, \
None)
except AttributeError:
raise AttributeError, \
"there is no '%s' builtin" % attr

allowing:
a=MyList()
a.append(12)
a.append(24)
a.len() 2 a.min() 12 a.max()

24

It works for all builtins that can take a list as a first argument.
Of course it should not be taken seriously :)
--
TZOTZIOY, I speak England very best,
Ils sont fous ces Redmontains! --Harddix
Jul 18 '05 #10

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

Similar topics

23
3566
by: Invalid User | last post by:
While trying to print a none empty list, I accidentaly put an "else" statement with a "for" instead of "if". Here is what I had: if ( len(mylist)> 0) : for x,y in mylist: print x,y else: print "Empty list" which was supposed to be:
27
3067
by: Ron Adam | last post by:
There seems to be a fair amount of discussion concerning flow control enhancements lately. with, do and dowhile, case, etc... So here's my flow control suggestion. ;-) It occurred to me (a few weeks ago while trying to find the best way to form a if-elif-else block, that on a very general level, an 'also' statement might be useful. So I was wondering what others would think of it.
38
5730
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
32
4128
by: James Curran | last post by:
I'd like to make the following proposal for a new feature for the C# language. I have no connection with the C# team at Microsoft. I'm posting it here to gather input to refine it, in an "open Source" manner, and in an attempt to build a ground-swell of support to convince the folks at Microsoft to add it. Proposal: "first:" "last:" sections in a "foreach" block The problem: The foreach statement allows iterating over all the...
43
2713
by: markryde | last post by:
Hello, I saw in some open source projects a use of "!!" in "C" code; for example: in some header file #define event_pending(v) \ (!!(v)->vcpu_info->evtchn_upcall_pending & \ !(v)->vcpu_info->evtchn_upcall_mask) whereas evtchn_upcall_pending is of type unsigned char (and also evtchn_upcall_mask is of type unsigned char).
7
12713
by: Girish Sahani | last post by:
Hi, Please check out the following loop,here indexList1 and indexList2 are a list of numbers. for index1 in indexList1: for index2 in indexList2: if ti1 == ti2 and not index1 != indexList1.pop(): index1+=1 index2+=1 continue
94
30272
by: Samuel R. Neff | last post by:
When is it appropriate to use "volatile" keyword? The docs simply state: " The volatile modifier is usually used for a field that is accessed by multiple threads without using the lock Statement (C# Reference) statement to serialize access. " But when is it better to use "volatile" instead of "lock" ?
5
2392
by: raylopez99 | last post by:
I understand delegates (static and non-static) and I agree they are very useful, and that the "Forms" used in the Windows .NET API could not work without them. That said, I'm curious as to how many heavy duty pro programmers in this newsgroup have actually used a delegate in their code, say in the last year of coding. By "use" I mean constructed a delegate and using it in an Event Source class and an Event Receiver class. Interfaces...
5
4057
by: Kyle Hayes | last post by:
Is there a way to use the 'r' in front of a variable instead of directly in front of a string? Or do I need to use a function to get all of the slashes automatically fixed? /thanks -Kyle
0
8428
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
8335
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
8851
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...
1
8528
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
8627
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
7356
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
4175
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...
1
2752
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
2
1976
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.