2016-11-18 6 views
0

Mein Code so weit:.Split-String in die Räume der Wahl mit Split ("", int)

firstname = 'Christopher Arthur Hansen Brooks'.split(' ',1) # [0] selects the first element of the list 
lastname = 'Christopher Arthur Hansen Brooks'.split(' ')[-1] # [-1] selects the last element of the list 
print(firstname) 
print(lastname) 

Ich möchte Ausgang:

['Christopher Arthur Hansen', 'Brooks'] 

Ich möchte, dass die Ausgabe von nur die Verwendung von split(' ', int) Methode. Wie kann ich es tun?

+1

Sie wollen also von rechts aufteilen? Haben Sie ['rsplit'] (https://docs.python.org/3/library/stdtypes.html#str.rsplit) berücksichtigt? – jonrsharpe

+0

Ich denke du willst ein Komma. '['Christopher Arthur Hansen', 'Brooks']' – pylang

Antwort

2

Sie könnten diese Ausgabe erhalten, indem rsplit verwenden und nur ein Split durchführen, das heißt:

'Christopher Arthur Hansen Brooks'.rsplit(' ', 1) 

, die eine Liste zurückgibt:

['Christopher Arthur Hansen', 'Brooks'] 

Dass man in firstname entpacken und lastname:

firstname, lastname = 'Christopher Arthur Hansen Brooks'.rsplit(' ', 1) 

Für Eingabe tha t könnte kurz sein (d. h. Benutzer gibt nur den Vornamen ein), ist es besser, rpartition zu verwenden, wenn Sie auch entpacken möchten; Das Entpacken muss einfach das zurückgegebene 3-Element-Tupel verarbeiten:

firstname, _, lastname = 'Christopher Arthur Hansen Brooks'.rpartition(' ') 
+2

Oder sogar '.rpartition ('')' wenn ein festes Ergebnis für Fälle benötigt wird, in denen ein leerer String vorhanden ist, oder kein Split gemacht werden kann usw. –