2011-01-25 6 views

Odpowiedz

41
firstpart, secondpart = string[:len(string)/2], string[len(string)/2:] 
+2

Albo nawet 'firstpart, secondpart = string [ :: 2], ciąg [1: 2] ', ponieważ pytanie nie określało, że części musiały być ciągłe. – Duncan

+0

@Duncan, :) dobra odpowiedź też .. :) –

+3

W python3: 'firstpart, secondpart = string [: len (string) // 2], string [len (string) // 2:]' – Omid

5
a,b = given_str[:len(given_str)/2], given_str[len(given_str)/2:] 
0

Innym możliwym rozwiązaniem jest użycie divmod. rem służy do dołączenia środkowego znaku do przodu (jeśli jest nieparzysty).

def split(s): 
    half, rem = divmod(len(s), 2) 
    return s[:half + rem], s[half + rem:] 

frontA, backA = split('abcde') 
0

W Pythonie 3:
Jeśli chcesz coś
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):]