Last modified: Jan 10, 2023 By Alexander Williams

How to Check if String Contains a Newline in Python

In python, the '\n' character represents a new line.

This tutorial will unveil different ways to check if a string contains a new line.

Let's get started.

Check if a string contains newlines using the 'in' operator

With the 'in' operator, we can check for a specified value in a string. However, this method returns True if the value exists. Otherwise, returns False.

Syntax

'\n' in my_string

Example

We'll check for a new line in the string using the  '\n' operator in the following example.

# String
my_string = '''
Python is an interpreted high-level general-purpose programming language. 
Its design philosophy emphasizes code readability with its use of significant indentation.
'''

# Check if Newline exists in my_string
print('\n' in my_string)

Output:

True

The output is True that's means my_string contains a new line.

Now, let's remove all new lines from the string and see the output.

# String
my_string = '''Python is an interpreted high-level general-purpose programming language. Its design philosophy emphasizes code readability with its use of significant indentation.'''

# Check if Newline is exists on my_string
print('\n' in my_string)

Output:

False

"Do something" example

If you want to do something after checking, see the following example:

# String
my_string = '''
Python is an interpreted high-level general-purpose programming language. 
Its design philosophy emphasizes code readability with its use of significant indentation.
'''

if '\n' in my_string:
    # Do something
    print(True)
else:
    # Do something
    print(False)

Output:

True

Check if a string contains newlines using Regex

we can also use Regex to check if a string contains a newline.

Syntax

# search function
re.search('\n', my_string)

# findall function
re.findall('\n', my_string)

search() function

search() returns the object if there is a match. Otherwise, it returns None.

This function will be helpful when you want to get the position of the first newline.

import re

# String
my_string = '''
Python is an interpreted high-level general-purpose programming language. 
Its design philosophy emphasizes code readability with its use of significant indentation.
'''

# Search Newlines on my_string
regex = re.search('\n', my_string)

# Result
print(regex)

Output:

<re.Match object; span=(0, 1), match='\n'>

findall() function

findall() Returns a list of all matches; otherwise, it returns an empty list.

 

import re

# String
my_string = '''
Python is an interpreted high-level general-purpose programming language. 
Its design philosophy emphasizes code readability with its use of significant indentation.
'''

# Find Newlines on my_string using findall()
regex = re.findall('\n', my_string)

# Result
print(regex)

Output:

['\n', '\n', '\n']

As you can see, the program found 3 new lines in my_string.