python check string ends with a newline character

Python – Check If String Ends with a Newline Character

In this tutorial, we will look at how to check if a string in Python ends with a newline character ('\n') or not with the help of some examples.

How to check if a string ends with a newline character?

python check string ends with a newline character

To check if a string in Python ends with a newline character or not, use the string endswith() function. Pass the newline character '\n' as an argument. The following is the syntax –

# check if string ends with a newline character
s.endswith('\n')

Alternatively, you can check if the last character in the string is a newline character or not using the equality operator ==. The following is the syntax –

# check if string ends with a newline character
s[-1] == '\n'

It returns True if the string ends with a newline character.

Examples

Let’s now look at some examples of using the above methods. First, we will create some strings that we will use throughout this tutorial.

# create strings
s1 = "Hello World\n"
s2 = "Hello World"
s3 = ""

# display the strings
print(s1)
print(s2)
print(s3)

Output:

Hello World

Hello World

Here, we created three strings – s1, s2, and s3. The string s1 ends with a newline character, the string s2 does not end with a newline character and the string s3 is an empty string.

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

Advanced ⭐⭐⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

Let’s now check if the above strings end with a newline character or not. First, we will use the endswith() method.

# check if string ends with a newline character
print(s1.endswith('\n'))
print(s2.endswith('\n'))
print(s3.endswith('\n'))

Output:

True
False
False

We get True for s1 as it does end with '\n'. We get False for s2 and s3 as they do not end with a '\n'.

Now let’s check the same using the 2nd method where we compare the last character to '\n'.

First, let’s do this for strings s1 and s2.

# check if string ends with a newline character
print(s1[-1] == '\n')
print(s2[-1] == '\n')

Output:

True
False

We get the correct result for them – True for s1 and False for s2.

Now let’s apply this method to the empty string s3.

# check if string ends with a newline character.
print(s3[-1] == '\n')

Output:

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
Input In [4], in <module>
      1 # check if string ends with a newline character.
----> 2 print(s3[-1] == '\n')

IndexError: string index out of range

We get an IndexError because we’re trying to access an index that does not exist (an empty string does not have a -1 index).

To avoid the above error, you can first check whether the string is non-empty and then proceed to check if the last character is a newline character or not. See the example below –

# function to check if string ends wtih a newline character
def check_str_ends_with_newline(s):
    if s and s[-1] == '\n':
        return True
    else:
        return False

# check if string ends with a newline character
print(check_str_ends_with_newline(s3))

Output:

False

We get False as the output for the empty string.

From the above examples, you can see that using the string endswith() function is the cleaner way of checking if a string ends with a newline character or not. Also, you don’t need to explicitly handle empty strings.

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

Scroll to Top