Hi I have a text file which has the following:

'username=sonia\n', 'password=password'

I want to split sonia and place it in a variable called username.

I was able to accomplish the following but could not remove the new line characters.

text = 'username=sonia\n', 'password=password'

text[0].split('=')[1]

This returns 'sonia\n'

So now how do I get rid of the \n?

What should be modified to also remove the new line '\n'?


Thanks in advance.

Sonia

Recommended Answers

All 3 Replies

If you know that there will always be a newline there, you could just splice the string that is returned.

text[0].split('=')[1][:-1]

that should work. This takes everything but the last char which is the newline.

-Michael

Member Avatar for masterofpuppets

hi,
another way is to use the .strip() method like this:

>>> n = "sonya\n"
>>> print n
sonya

>>> a = n.strip()
>>>print a
sonya
>>>

.strip() also removes leading or trailing whitespaces

hope this helps :)

Micheal, Nice, very nice, this worked.

Thanks,
Sonia

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.