3 Replies - 5082 Views - Last Post: 22 June 2011 - 09:49 AM Rate Topic: -----

#1 tootypegs  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 239
  • Joined: 09-October 07

how do you join strings without the \n

Posted 22 June 2011 - 06:09 AM

im trying to join a string together by reading the middle part from a file. However the output is not as i expected as i think there is a /n on the end of the word i extract from the file. For example, with the code below i would like to get

hellotheredog

but i get

hellothere
dog

the next line character is breaking up my string, is there a way to remove it?


logfileforkeywords = open('C:\\records.txt', 'r')
line = logfileforkeywords.readlines()
for lines in line:
   stri = 'hello' + lines + 'dog'



cheers guys

Is This A Good Question/Topic? 0
  • +

Replies To: how do you join strings without the \n

#2 Brewer  Icon User is offline

  • Awesome
  • member icon

Reputation: 178
  • View blog
  • Posts: 1,044
  • Joined: 14-June 10

Re: how do you join strings without the \n

Posted 22 June 2011 - 06:25 AM

All you need to do is switch stri with a print statement and use .strip() when calling lines.

f = open('C:\\records.txt', 'r')

for line in f:
    print "Hello" + line.strip() + "dog"


This post has been edited by Brewer: 22 June 2011 - 06:32 AM

Was This Post Helpful? 1
  • +
  • -

#3 Motoma  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 452
  • View blog
  • Posts: 796
  • Joined: 08-June 10

Re: how do you join strings without the \n

Posted 22 June 2011 - 06:25 AM

You will want to strip() your lines before concatenating them:
>>> "this is a string with a trailing newline\n"
'this is a string with a trailing newline\n'
>>> "this is a string with a trailing newline\n".strip()
'this is a string with a trailing newline'


Was This Post Helpful? 1
  • +
  • -

#4 Nallo  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 161
  • View blog
  • Posts: 247
  • Joined: 19-July 09

Re: how do you join strings without the \n

Posted 22 June 2011 - 09:49 AM

strip() removes all leading and trailing whitespace. You may want to use rstrip("\n") instead:
>>> " blah \n"
' blah \n'
>>> " blah \n".strip()
'blah'
>>> " blah \n".rstrip("\n")
' blah '



Or to make it operation system independent (\n is linebreak on *nix, but mac os and windows use a different one):
>>> import os
>>> " blah \n".rstrip(os.linesep)
' blah '


Was This Post Helpful? 1
  • +
  • -

Page 1 of 1