Is there a way to split a string开发者_运维百科 into 2 equal halves without using a loop in Python?
Python 2:
firstpart, secondpart = string[:len(string)/2], string[len(string)/2:]
Python 3:
firstpart, secondpart = string[:len(string)//2], string[len(string)//2:]
Whoever is suggesting string[:len(string)/2], string[len(string)/2]
is not keeping odd length strings in mind!
This works perfectly. Verified on edx.
first_half = s[:len(s)//2]
second_half = s[len(s)//2:]
a,b = given_str[:len(given_str)/2], given_str[len(given_str)/2:]
Another possible approach is to use divmod. rem is used to append the middle character to the front (if odd).
def split(s):
half, rem = divmod(len(s), 2)
return s[:half + rem], s[half + rem:]
frontA, backA = split('abcde')
In Python 3:
If you want something like
madam => ma d am
maam => ma am
first_half = s[0:len(s)//2]
second_half = s[len(s)//2 if len(s)%2 == 0 else ((len(s)//2)+1):]
minor correction the above solution for below string will throw an error
string = '1116833058840293381'
firstpart, secondpart = string[:len(string)/2], string[len(string)/2:]
you can do an int(len(string)/2)
to get the correct answer.
firstpart, secondpart = string[:int(len(string)/2)], string[int(len(string)/2):]
精彩评论