python find if newline is in string
23,220
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
.
Author by
rishubk
Updated on August 01, 2020Comments
-
rishubk almost 4 years
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