473,661 Members | 2,501 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

spliting on ":"

hi

i have a file with

xxx.xxx.xxx.xxx :yyy
xxx.xxx.xxx.xxx :yyy
xxx.xxx.xxx.xxx :yyy
xxx.xxx.xxx.xxx
xxx.xxx.xxx.xxx
xxx.xxx.xxx.xxx :yyy

i wanna split on ":" and get all the "yyy" and print the whole line out
so i did

print line.split(":")[-1]

but line 4 and 5 are not printed as there is no ":" to split. It should
print a "blank" at least.
how to print out lines 4 and 5 ?
eg output is

yyy
yyy
yyy
yyy

thanks

Mar 4 '06 #1
11 1350
s9************@ yahoo.com wrote:
print line.split(":")[-1]

but line 4 and 5 are not printed as there is no ":" to split. It should
print a "blank" at least.
how to print out lines 4 and 5 ?
eg output is

yyy
yyy
yyy
yyy


if ":" in line:
print line.split(":")[-1]
else:
print

what's the problem?
Mar 4 '06 #2
s9************@ yahoo.com wrote:
hi

i have a file with

xxx.xxx.xxx.xxx :yyy
xxx.xxx.xxx.xxx :yyy
xxx.xxx.xxx.xxx :yyy
xxx.xxx.xxx.xxx
xxx.xxx.xxx.xxx
xxx.xxx.xxx.xxx :yyy

i wanna split on ":" and get all the "yyy" and print the whole line out
so i did

print line.split(":")[-1]

but line 4 and 5 are not printed as there is no ":" to split. It should
print a "blank" at least.
how to print out lines 4 and 5 ?
eg output is

yyy
yyy
yyy
yyy


That's not what I get:

In [2]: data='''xxx.xxx .xxx.xxx:yyy
...: xxx.xxx.xxx.xxx :yyy
...: xxx.xxx.xxx.xxx :yyy
...: xxx.xxx.xxx.xxx
...: xxx.xxx.xxx.xxx
...: xxx.xxx.xxx.xxx :yyy'''.splitli nes()

In [3]: for line in data:
...: print line.split(':')[-1]
...:
...:
yyy
yyy
yyy
xxx.xxx.xxx.xxx
xxx.xxx.xxx.xxx
yyy

Kent
Mar 4 '06 #3
Cyril Bazin wrote:
Your file looks like a list of IP adresses.
You can use the urllib and urllib2 modules to parse IP adresses.

import urllib2
for line in open("fileName. txt"):
addr, port = urllib2.splitpo rt(line)
print (port != None) and '' or port


Is this what you want to happen when port is None?
port = None
print (port != None) and '' or port

None
I think you're getting caught by the classic and/or trap in Python,
trying to avoid using a simple if statement.

By the way, equality comparison with None is generally a bad idea as
well, so even if the above worked it should be (port is not None) rather
than (port != None).

-Peter

Mar 4 '06 #4
> I think you're getting caught by the classic and/or trap in Python,
trying to avoid using a simple if statement.


What do you mean by "the classic and/or trap"? Can you give an example
please?

Petr Jakes

Mar 4 '06 #5
Cyril Bazin wrote:
Ok, ok, there was a mistake in the code.
(Of course, it was done on prupose in order to verify if everybody is
aware ;-)
I don't know why it is preferable to compare an object to the object
"None" using "is not".
"==" is, IMHO, more simple. Simple is better than complex.. So I use "==".
The archives could tell you more, but basically on is usually interested
in *identity* with a singleton object (None), not in whether the object
on is examining happens to compare equal. A custom object could be
designed to compare equal to None in certain cases, even though it *is
not* None, leading to the "== None" approach being defective code.

In the specific code in question, it won't make any differences, but I
pointed it out to help folks who don't know this to start developing the
safer habit, which is always to use "is" and "is not" with None (or,
generally, with other singletons).
The correct program is:

import urllib2
for line in open("fileName. txt"):
addr, port = urllib2.splitpo rt (line)
print (port == None) and '' or port
Nope, sorry... the point is that the "and/or" pseudo-ternary operator is
inherently flawed if the operand after "and" evaluates False. Check
this out:
port = None
print (port == None) and '' or port None print (port != None) and '' or port None

and even:
print (port is None) and '' or port

None

So the bug isn't in using "!=" instead of "==", or using equality
instead of identity comparison, it is in trying to use the and/or
expression for a purpose it wasn't intended for.
or

import urllib2
for line in open("fileName. txt"):
addr, port = urllib2.splitpo rt(line)
if port == None:
print ''
else:
print port


That should work nicely... and it's more readable too!

Note that in Python 2.5 you should be able to write this as

print '' if port is None else port
or print '' if (port is None) else port

but it's quite arguable whether that is better than the simple if/else
statement in this case.

-Peter

Mar 5 '06 #6
Petr Jakes wrote:
I think you're getting caught by the classic and/or trap in Python,
trying to avoid using a simple if statement.


What do you mean by "the classic and/or trap"? Can you give an example
please?


Sure, see my subsequent reply to Cyril, elsewhere in this thread.

(In summary, and/or is defective when used as a ternary operator if the
expression after "and" evaluates False. The list archives can tell you
more.)

-Peter

Mar 5 '06 #7
On Sat, 04 Mar 2006 08:54:33 -0800, s99999999s2003 wrote:
hi

i have a file with

xxx.xxx.xxx.xxx :yyy
xxx.xxx.xxx.xxx :yyy
xxx.xxx.xxx.xxx :yyy
xxx.xxx.xxx.xxx
xxx.xxx.xxx.xxx
xxx.xxx.xxx.xxx :yyy

i wanna split on ":" and get all the "yyy" and print the whole line out
so i did

print line.split(":")[-1]

but line 4 and 5 are not printed as there is no ":" to split. It should
print a "blank" at least.
how to print out lines 4 and 5 ?
eg output is

yyy
yyy
yyy
yyy

There are a few ways of handling this problem. It depends on what you want
to do if your input string looks like this "abc:y:z": should your code
print "y", "z" or even "y:z"?

# look before you leap
line = "abc:y:z"
if ":" in line:
print line.split(":")[-1] # prints "z"
print line.split(":")[1] # prints "y"
print line.split(":", 1)[-1] # prints "y:z"
# if your line only has one colon, the above three lines
# should all print the same thing
else:
print ""

# look before you leap again
L = line.split(":")
if len(L) > 1:
print L[1]
else:
print ""

# use a sentinel value
print (line + ":").split( ":", 1)[1][:-1]
--
Steven.

Mar 5 '06 #8
yyy
yyy
yyy
xxx.xxx.xxx.xxx
xxx.xxx.xxx.xxx


of course you will get this result...

inside the loop, when line="xxx.xxx.x xx.xxx:yyy"
line.split(":") will give a list ["xxx.xxx.xxx.xx x", "yyy"], and
element -1 will be "yyy"

but when line="xxx.xxx.x xx.xxx"
line.split(":") will give a list ["xxx.xxx.xxx.xx x"], and element -1
will be "xxx.xxx.xxx.xx x"

So the result is very very normal

Mar 6 '06 #9
Peter Hansen wrote:
The archives could tell you more, but basically on is usually interested
in *identity* with a singleton object (None), not in whether the object
on is examining happens to compare equal. A custom object could be
designed to compare equal to None in certain cases, even though it *is
not* None, leading to the "== None" approach being defective code.
But if a custom class allows instances to compare as equal to None,
we might reasonably expect the programmers had a reason. There's not
much anyone can do with None besides passing it around and comparing
it by value or identity. Insisting on 'is' rather than '==' will break
whatever polymorphism such a custom object was trying to achieve.

In the specific code in question, it won't make any differences, but I
pointed it out to help folks who don't know this to start developing the
safer habit, which is always to use "is" and "is not" with None (or,
generally, with other singletons).


Hmmm... To make my code safer, I'm thinking I should replace doc strings
that say "if bluf is Null" with "if blurf compares equal to Null".
--
--Bryan

Mar 6 '06 #10

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

Similar topics

6
1852
by: Brad Kent | last post by:
Anyone out there have any tricks or scripts to take some text of unknown length and display it in two (or more) columns of equal height? The text may or may not contain "hard-coded" linebreaks or other formatting such as s. why there's not a columns tag in HTML is mystery <COLUMNS col=3> wouldn't this be grand </COLUMNS>
43
5084
by: steve | last post by:
I am quite frustrated with php’s include, as I have spent a ton of time on it already... anyone can tell me why it was designed like this (or something I don’t get)? The path in include is relative NOT to the immediate script that is including it, but is relative to the top-level calling script. In practice, this means that you have to constantly worry and adjust paths in includes, based on the startup scripts that call these...
1
8060
by: David Furey | last post by:
Hi I have an XML documnet and a XSLT document as shown below THe XSLT document brings back a filtered docmument that has the VendorName that starts with a particular sub-string This works as expected with alphabet and number characters and the ' (single quote &apos; entity) character but does not work if a double quote character " is part of the string to filter on This returns all Vendor Names that begin with A (either case)
3
3635
by: NecroJoe | last post by:
I am using PHP to generate a little javascript for one of my pages. In short it allows a user to select a value from a list and pop it into a form field on a seperate page. This works well unless there is a " or ' in the character string. <SCRIPT language=JavaScript> function Add_Term(SearchTerm) { window.opener.document.advsearch.name_title.value += SearchTerm; window.close();
5
3457
by: Mateusz Loskot | last post by:
Hi, I'd like to ask how XML parsers should handle attributes which consists of &quot; entity as value. I know XML allows to use both: single and double quotes as attribute value terminator. That's clear. But how should parser react for such situation: I have CORDSYS element with string attribute which consists of value with many &quot; entities:
3
2699
by: Arpi Jakab | last post by:
I have a main project that depends on projects A and B. The main project's additional include directories list is: ...\ProjectA\Dist\Include ...\ProjectB\Dist\Include Each of the include directories contain a file named "cppfile1.h". In my main project I #include "cppfile1.h". I rely on the order of paths in additional include directories list to get file cppfile1.h from ProjectA and
5
3431
by: martin | last post by:
Hi, I would be extremly grateful for some help on producing an xml fragemt. The fragment that I wish to produce should look like this <Addresses> <Address>&qout;Somebody's Name&quot; &lt;me@mydomain.com&gt;</Address> </Addresses>
8
3611
by: Ulysse | last post by:
Hello, I need to clean the string like this : string = """ bonne mentalit&eacute; mec!:) \n <br>bon pour info moi je suis un serial posteur arceleur dictateur ^^* \n <br>mais pour avoir des resultats probant il faut pas faire les mariolles, comme le &quot;fondateur&quot; de bvs
1
2835
by: manchin2 | last post by:
Hi, Can anybody please provide the information about "&quot" and its use, if possible please provide an example. 1)<tm:bom-expression>{Conf.getEquityConfLookupFields().getEventFieldText(&quot;AdditionalDisruption&quot;,&quot;Change in Law&quot;)}</tm:bom-expression> 2)07:41:08 Default ( call ( . ( call ( . Conf getEquityConfLookupFields ) ) getEventFieldText ) ( , AdditionalDisruption Change inLaw ) ) value=Not applicable Can you please...
4
3883
by: fran7 | last post by:
Hi, from help in the javascript forum I found the error in some code but need help. This bit of code works perfectly, trouble is I am writing it to a javascript function so the height needs to be in &quot;&quot; instead of "" otherwise I get an error message. Can anyone suggest how to write it so that it writes &quot; instead of "". I have tried all combinations of adding &quot; to the code but as soon as I think I am there I get throw out again. if...
0
8343
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
8855
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
7364
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
6185
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
5653
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
4179
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
4346
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2762
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
1986
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.