To split a long string into lines in Python, you can use the splitlines()
method or the split()
method with the '\n'
character as the delimiter. Here’s an example using splitlines()
:
my_string = "This is a long string.\nIt has multiple lines.\nEach line ends with a newline character.\n"
# Split the string into lines
lines = my_string.splitlines()
print(lines) # Output: ['This is a long string.', 'It has multiple lines.', 'Each line ends with a newline character.']
In this example, we define a string my_string
that contains multiple lines separated by newline characters. We use the splitlines()
method to split the string into a list of lines, which is stored in the lines
variable.
Alternatively, you can use the split()
method with the '\n'
character as the delimiter:
my_string = "This is a long string.\nIt has multiple lines.\nEach line ends with a newline character.\n"
# Split the string into lines
lines = my_string.split('\n')
print(lines) # Output: ['This is a long string.', 'It has multiple lines.', 'Each line ends with a newline character.', '']
In this example, we use the split()
method with the '\n'
character as the delimiter to split the string into a list of lines. Note that this method results in an empty string at the end of the list due to the trailing newline character in my_string
.
Either method should work for splitting a long string into lines in Python.
+ There are no comments
Add yours