#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2004
    Location
    Bombay, India
    Posts
    159
    Rep Power
    12

    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. #2
  3. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    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.
    programming language development: www.netytan.com – Hula

  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2004
    Location
    Bombay, India
    Posts
    159
    Rep Power
    12
    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
  6. #4
  7. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    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 11:51 AM.
    programming language development: www.netytan.com – Hula

  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Feb 2004
    Location
    London, England
    Posts
    1,585
    Rep Power
    1373
    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
  10. #6
  11. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2004
    Location
    Bombay, India
    Posts
    159
    Rep Power
    12
    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
  12. #7
  13. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2003
    Posts
    624
    Rep Power
    34
    I mean give me a reason as to why one shd go for the file() function.
    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.
  14. #8
  15. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    A little cheesy to quote urself but still. I quote .

    Originally Posted by netytan
    On this subject you should really be using file() instead of open() since it's depreciated, and will eventually disappear.
    programming language development: www.netytan.com – Hula

  16. #9
  17. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2004
    Location
    Bombay, India
    Posts
    159
    Rep Power
    12
    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
  18. #10
  19. Mini me.
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2003
    Location
    Cambridge, UK
    Posts
    783
    Rep Power
    13
    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.
  20. #11
  21. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Feb 2004
    Location
    London, England
    Posts
    1,585
    Rep Power
    1373
    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/pyt...ly/045921.html

    and quote from a later post in the thread:

    > I have always used open() myself. does this mean we should continue
    > to use open()?

    IMO, yes. My posting was intended to draw attention to the fact that
    apparently some developers think differently. I'm hoping to revert
    their opinions unless there's a really good reason to switch to
    file().

    --Guido van Rossum (home page: http://www.python.org/~guido/)
    Dave - The Developers' Coach
    Last edited by DevCoach; November 4th, 2004 at 02:57 AM.
  22. #12
  23. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    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.
    programming language development: www.netytan.com – Hula

  24. #13
  25. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2004
    Location
    Bombay, India
    Posts
    159
    Rep Power
    12
    That was very informative Dave!!!
    I wld definitely go with the developer of Python ...unless I get a valid reason to change to file()

    Thanks,
    Subha
  26. #14
  27. Mini me.
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2003
    Location
    Cambridge, UK
    Posts
    783
    Rep Power
    13
    And a document glitch that gets reproduced every where (and I suspect not identified because of it's "correctness") did not help.

    [Not every thing is smooth in the real world just look at decorators!]

    grimey

IMN logo majestic logo threadwatch logo seochat tools logo