4

I am trying to find if a "\n" character is in a string using this:

if "\n" in errors.text

This works fine for a string like "one\ntwo" but when the newline is at the end of the string like "one\n", it doesn't seem to work. I am using selenium to get this string from a website. Is it possible that it is not catching the newline at the end and simply not including it?

Or could this be the problem?

fixedText = errors.text.split("\n")[0]

I want the fixed text to remove all newlines and only get the first line of text. It works except for the case discussed above

7
  • "\n" in "one\n" works fine. Commented Aug 1, 2015 at 7:04
  • well im getting the data from a website, so is it possible that it is not catching the newline at the end of the string from the website Commented Aug 1, 2015 at 7:05
  • If the string is literally \ and n, you should use "\\n" in errors.text or r"\n" in errors.text Commented Aug 1, 2015 at 7:07
  • no its actually just a return Commented Aug 1, 2015 at 7:10
  • Is there chance that the page does not contain newline at all? Commented Aug 1, 2015 at 7:22

1 Answer 1

4

If you want the fixed text to only be the first line in a string, you can do this:

if errors.text: # skips empty strings
    fixedText = errors.text.split("\n")[0]

This is because split() is reasonably robust:

>>> 'a'.split()[0]
'a'
>>> 'a\n'.split()[0]
'a'
>>> 'a\n1'.split()[0]
'a'
>>> ''.split()
[]

That last example demonstrates why we check for an empty string before trying to index the resulting list.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.