I need to split a string in half which I've already done with:
firstpart, secondpart = string[:len(string)//2], string[len(string)//2:]
I need it to split at a line break and I'm too new at coding to know how to approach this. Any tips would help.
I need to split a string in half which I've already done with:
firstpart, secondpart = string[:len(string)//2], string[len(string)//2:]
I need it to split at a line break and I'm too new at coding to know how to approach this. Any tips would help.
Assuming the string has only one line break.
That would be:
firstpart, secondpart = string.split('\n')
you can use the splitlines method which will work perfectly in your case,
str1="hope\n this helps\n you"
print(str1.splitlines())
output:
['hope', ' this helps', ' you']
It returns a list of splitted string.
Hope this helps you!
Try something like this:
mystring = """Mae hen wlad fy nhadau yn annwyl i mi,
Gwlad beirdd a chantorion, enwogion o fri;
Ei gwrol ryfelwyr, gwladgarwyr tra mad,
Dros ryddid collasant eu gwaed.
Gwlad!, GWLAD!, pleidiol wyf i'm gwlad.
Tra mor yn fur i'r bur hoff bau,
O bydded i'r hen iaith barhau.
Hen Gymru fynyddig, paradwys y bardd,
Pob dyffryn, pob clogwyn, i'm golwg sydd hardd;
Trwy deimlad gwladgarol, mor swynol yw si
Ei nentydd, afonydd, i fi.
"""
# get the half-way index
halfway = len(mystring) // 2
# get the indices of the nearest \n characters before and after the halfway
try:
next_one = mystring.index("\n", halfway)
except ValueError:
next_one = None
try:
previous_one = mystring.rindex("\n", 0, halfway)
except ValueError:
previous_one = None
# if no \n found at all, raise an error
if next_one == None and previous_one == None:
raise ValueError
# or if a \n is only found on one side of halfway, use that one
elif next_one == None:
pos = previous_one
elif previous_one == None:
pos = next_one
# or if it is found on both sides of half-way, use whichever is nearer
elif next_one - halfway < halfway - previous_one:
pos = next_one
else:
pos = previous_one
# now actually split the string
part1 = mystring[:pos]
part2 = mystring[pos + 1:]
print("FIRST HALF:", part1)
print("==========")
print("SECOND HALF:", part2)
Gives:
FIRST HALF: Mae hen wlad fy nhadau yn annwyl i mi,
Gwlad beirdd a chantorion, enwogion o fri;
Ei gwrol ryfelwyr, gwladgarwyr tra mad,
Dros ryddid collasant eu gwaed.
Gwlad!, GWLAD!, pleidiol wyf i'm gwlad.
==========
SECOND HALF: Tra mor yn fur i'r bur hoff bau,
O bydded i'r hen iaith barhau.
Hen Gymru fynyddig, paradwys y bardd,
Pob dyffryn, pob clogwyn, i'm golwg sydd hardd;
Trwy deimlad gwladgarol, mor swynol yw si
Ei nentydd, afonydd, i fi.