2

How can I delete a /n linebreak at the end of a String ?

I´m trying to read two strings from an .txt file and want to format them with os.path.join() method after I "cleared" the string.

Here you can see my try with dummy data:

content = ['Source=C:\\Users\\app\n', 'Target=C:\\Apache24\\htdocs']

for string in content:
    print(string)
    if string.endswith('\\\n'):
        string = string[0:-2]

print(content)
JohnDizzle
  • 1,268
  • 3
  • 24
  • 51
  • 2
    I think you're trying to modify the iterator rather than the contents, besides this does what you want: `[x.rstrip('\n') for x in content]` – EdChum Dec 15 '15 at 09:32

4 Answers4

4

You can not update a string like you are trying to. Python strings are immutable. Every time you change a string, new instance is created. But, your list still refers to the old object. So, you can create a new list to hold updated strings. And to strip newlines you can use rstrip function. Have a look at the code below,

content = ['Source=C:\\Users\\app\n', 'Target=C:\\Apache24\\htdocs']
updated = []
for string in content:
    print(string)
    updated.append(string.rstrip())

print(updated)
Hossain Muctadir
  • 3,546
  • 1
  • 19
  • 33
3

You can use rstrip function. it trims any 'empty' string including \n from the string, like below:

>>> a = "aaa\n"
>>> print a
aaa
>>> a.rstrip()
'aaa'
resec
  • 2,091
  • 3
  • 13
  • 22
1

To remove only \n use this:

string = string.rstrip('\n')
Kenly
  • 24,317
  • 7
  • 44
  • 60
0

When you do string[0:-2] you are actually removing 2 characters from the end, while \n is one character.

try:

content = map(lambda x: x.strip(), content)
mirosval
  • 6,671
  • 3
  • 32
  • 46