|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
string concatenation!
Suppose I've this text in a file:
A car is traveling at a uniform speed. The driver sees a mile- stone showing a 2-digit number. After traveling for an hour the driver sees another milestone with the same digits in reverse order. After another hour the driver sees ano- ther milestone containing the same 2-digits with a zero in between(0). What is the average speed of the driver. Ans: 45 kmph Now whenever a hypen occurs at the end of the line I've to join the next string to it & the concatenated output goes to another file. So cld any Python expert do it for me? Thanks & Rgds, Subha ![]() |
|
#2
|
||||
|
||||
|
Well, I don't think anyone of us would use concatenation for this problem when it would be so much easier to simply use replace().
Code:
>>> carString = """A car is traveling at a uniform speed. The driver sees a mile-
stone showing a 2-digit number. After traveling for an hour the driver sees another milestone with the same digits in reverse order. After another hour the driver sees ano-
ther milestone containing the same 2-digits with a zero in between(0). What is the average speed of the driver."""
>>>
>>> carString.replace('-\n', '')
'A car is traveling at a uniform speed. The driver sees a milestone showing a 2-digit number. After traveling for an hour the driver sees another milestone with the same digits in reverse order. After another hour the driver sees another milestone containing the same 2-digits with a zero in between(0). What is the average speed of the driver.'
>>>
This doesn't bother with any file() handling, but that’s simple enough . Anyway, if you really want to use concatenation let me know, but I think this way is a bit better .Also Subha, could I ask what this is for since it looks a little like homework. Later, Mark. |
|
#3
|
|||
|
|||
|
Hi Mark,
This is how I did it...I know its not good programming here...as it increases the lines of code.... Code:
>>> def _fJoin(fin,fout):
... fp=open(fin,'r')
... fpo=open(fout,'w')
... lines=[]
... for line in fp.read():
... lines.append(str(line))
... for char in range(len(lines)-1):
... if lines[char]=='-':
... if lines[char+1]=='\n':
... lines[char]=''
... lines[char+1]=''
... else:pass
... else:pass
... fpo.write(''.join(lines))
... fpo.close()
then I used ur trick with the files.... Code:
>>> def markJoin(fin,fout):
... fp=open(fin,'r')
... fpo=open(fout,'w')
... lines=[]
... for line in fp.read():
... lines.append(str(line))
... lines2=string.join(lines,'')
... produce=lines2.replace('-\n','')
... fpo.write(produce)
... fpo.close()
... fp.close()
and both the programs gave the same output ... but thats not what I want... If this is the input--------------> A man was going by a bi-cycle. After going 2/3rd of total distance the bi-cycle broke down and he had to com- plete the journey on foot. At the end he found that he wal- ked twice as long as he was on bi-cycle. How many times the speed of the bi-cycle is as the speed of walking? and in the o/p the lines r joined which I don't want. for eg here, I wld want 'plete' to replace the '-' and the next line shd remain in its position itself but shifted to the left. Hope u r getting what I'm trying to explain.... And as for ur curiosity Mark, nope this is not a homework...this was a part of the program which I had to clear to get into my present company...n I did that using C...using the fgets() function to get the first word from the next line...n that had to be done in a single pass...with many other manipulations...I was trying to do it in Python...thats all! Cld u help now...as I'm at my wits end! Thanks & Rgds, Subha ![]() |
|
#4
|
||||
|
||||
|
Had to check
. Anyway, since it's just for curiosity here's a second way to do this (including a list comprehension). We could of course do this in even more ways but we're going to get less and less Pythonic here ...Code:
#!/usr/bin/env python
carString = """A car is traveling at a uniform speed. The driver sees a mile-
stone showing a 2-digit number. After traveling for an hour the driver sees another milestone with the same digits in reverse order. After another hour the driver sees ano-
ther milestone containing the same 2-digits with a zero in between(0). What is the average speed of the driver."""
token = '-\n'
results = []
for subString in carString.split(token):
subString = subString.split(' ', 1)
results.append('\n'.join(subString))
print ''.join(results)
print ''.join(['\n'.join(s.split(' ', 1)) for s in carString.split(token)])
Again, it doesn't include file handling but you should be able to work that out .On this subject you should really be using file() instead of open() since it's depreciated, and will eventually disappear. You should also recognize that the read() method returns a string – not a line. Just a thought .Hope this helps new, Mark. Last edited by netytan : November 2nd, 2004 at 12:51 PM. |
|
#5
|
|||
|
|||
|
Alternatively you could use the textwrap module, which will wrap a paragraph of text to a give line width.
e.g.: Code:
import textwrap
string = """A car is traveling at a uniform speed. The driver sees a mile-
stone showing a 2-digit number. After traveling for an hour the driver sees another milestone with the same digits in reverse order. After another hour the driver sees ano-
ther milestone containing the same 2-digits with a zero in between(0). What is the average speed of the driver."""
string = string.replace('-\n', '')
string = string.replace('\n', '')
string = textwrap.fill(string, 65)
This will not do what the original requirements ask for, but will probably do what the customer actually wants - an important distinction. Dave - The Developers' Coach |
|
#6
|
|||
|
|||
|
Thanks Mark...I got it using files....
But I can't figure out the difference between file n open functions....both are the same right... Code:
>>> fp=open('c:\\python23\\scripts\\test.txt','r')
>>> fp
<open file 'c:\python23\scripts\test.txt', mode 'r' at 0x01175C60>
>>> fp=file('c:\\python23\\scripts\\test.txt','r')
>>> fp
<open file 'c:\python23\scripts\test.txt', mode 'r' at 0x01175C20>
I mean give me a reason as to why one shd go for the file() function. And thanks Dave for introducing me to textwrap and a last word.....if the customer is clear of his requirements it wld well match the original requirements...I believe!! Thanks, Subha ![]() |
|
#7
|
|||
|
|||
|
Quote:
They both do the same thing now, but open() is older and was replaced with file(). open() is only being kept around for a while for compatability, but it is deprecated and with some future revision of Python it could stop working completely - so it's not recommended to rely on it. |
|
#8
|
||||
|
||||
|
A little cheesy to quote urself but still. I quote
.Quote:
|
|
#9
|
|||
|
|||
|
Actually what was asked was .... what is the USP of file() over open()...has to be something thats why open() is being scorned upon....
Anyway, thanks I shall let it pass!!! Subha |
|
#10
|
||||
|
||||
|
The USP is that the name file describes the object more accurately (it's a noun) than open (a verb) which wrongly describes an action on the object it is assigned to.
Think of it as rebranding to achieve greater market acceptance. ![]()
__________________
*** Experimental Python Markup CGI V2 *** |
|
#11
|
|||
|
|||
|
open has NOT been deprecated in favour of file.
GvR (the creator of Python) has said that open() should be used in preference to file(). This is because 'file' is the type of the object returned by open(), so you can call its constructor to create a new file object just as you can with any other python type, while open() is a factory function that may be extended in the future to create other file-like objects. http://mail.python.org/pipermail/py...uly/045921.html and quote from a later post in the thread: Quote:
Dave - The Developers' Coach Last edited by DevCoach : November 4th, 2004 at 03:57 AM. |
|
#12
|
||||
|
||||
|
I stand corrected
. Thanks for the new info Dave, and for the Guido quote .So, if open() may still change in the way it works but file() will always do exactly that – it seems like a good enough reason to stick with file() for now . Still I think it'll be quite a while untill open() really changes: bring on Python 3!Mark. |
|
#13
|
|||
|
|||
|
That was very informative Dave!!! I wld definitely go with the developer of Python ...un |