How to Read the First Line of a String in Python?

Estimated read time 1 min read

You can read the first line of a string in Python using the split() method and indexing. Here’s an example:

s = 'Hello\nWorld\n!'
first_line = s.split('\n')[0]
print(first_line) # Output: 'Hello'

In this example, we have a string (s) that contains three lines of text. We want to read the first line of the string. We achieve this by using the split() method with the newline character (\n) as the separator. The split() method returns a list of strings, where each string is a line of text from the original string. We use indexing ([0]) to select the first string in the list, which is the first line of text from the original string. The resulting string contains only the first line of text from the original string.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply