How can I check for a new line in string in Python 3.x?
Question:
How to check for a new line in a string?
Does python3.x have anything similar to java’s regular operation where direct if (x=='*n')
would have worked?
Answers:
If you just want to check if a newline (n
) is present, you can just use Python’s in
operator to check if it’s in a string:
>>> "n" in "hellongoodbye"
True
… or as part of an if
statement:
if "n" in foo:
print "There's a newline in variable foo"
You don’t need to use regular expressions in this case.
Yes, like this:
if 'n' in mystring:
...
(Python does have regular expressions, but they’re overkill in this case.)
See:
https://docs.python.org/2/glossary.html#term-universal-newlines
A manner of interpreting text streams in which all of the following are recognized as ending a line: the Unix end-of-line convention ‘n’, the Windows convention ‘rn’, and the old Macintosh convention ‘r’. See PEP 278 and PEP 3116, as well as str.splitlines() for an additional use.
I hate to be the one to split hairs over this (pun intended), but this suggests that a sufficient test would be:
if 'n' in mystring or 'r' in mystring:
...
What about this, using str methods?
if len(mystring.splitlines()) > 1:
print("found line breaks!")
How to check for a new line in a string?
Does python3.x have anything similar to java’s regular operation where direct if (x=='*n')
would have worked?
If you just want to check if a newline (n
) is present, you can just use Python’s in
operator to check if it’s in a string:
>>> "n" in "hellongoodbye"
True
… or as part of an if
statement:
if "n" in foo:
print "There's a newline in variable foo"
You don’t need to use regular expressions in this case.
Yes, like this:
if 'n' in mystring:
...
(Python does have regular expressions, but they’re overkill in this case.)
See:
https://docs.python.org/2/glossary.html#term-universal-newlines
A manner of interpreting text streams in which all of the following are recognized as ending a line: the Unix end-of-line convention ‘n’, the Windows convention ‘rn’, and the old Macintosh convention ‘r’. See PEP 278 and PEP 3116, as well as str.splitlines() for an additional use.
I hate to be the one to split hairs over this (pun intended), but this suggests that a sufficient test would be:
if 'n' in mystring or 'r' in mystring:
...
What about this, using str methods?
if len(mystring.splitlines()) > 1:
print("found line breaks!")