Wie kann man in Python Strings zerteilen?

2 Antworten

Vom Fragesteller als hilfreich ausgezeichnet

Ich denke es gibt in Python, wie in anderen Programmiersprachen auch, die String split() Methode. Habe mal schnell gegoogelt:
http://www.pythonforbeginners.com/dictionary/python-split
https://www.tutorialspoint.com/python/string_split.htm

das geht aber vermutlich nur mit Delimetern, bestimmten Trennzeichen.

Das was du suchst ist wohl die String Manipulation, wofür es in Python offensichtlich einige nützliche Methoden gibt. Hier wohl das passende für dich:

word = "Hello World"

print word[0] #get one char of the word
print word[0:1] #get one char of the word (same as above)
print word[0:3] #get the first three char
print word[:3] #get the first three char
print word[-3:] #get the last three char
print word[3:] #get all but the three first char
print word[:-3] #get all but the three last character

Ein String ist in Python also automatisch auch ein Array von Chars, du kannst also auf einzelne Buchstaben sehr einfach zugreifen. zB mit word[3]

Zusätzlich geht das aber auch für mehrere Buchstaben deines Strings:

word = "Hallo"

print word[:-2]
print word[3:]

und mit len(word) kannst du die ersten 3 auch wegschneiden ohne zu wissen wie lang der String ist (soft statt hard coding)

Habe noch nie mit Python gearbeitet, dies könnte aber so funktionieren:

word = "Hallo"

print word[:-2]
print word[len(word)-2:]

hoffe ich und Google konnten dir weiterhelfen ;)

~Tim

>>> s='Hallo'
>>> a=[s[:-2],s[-2::1]]
>>> print(a)
['Hal', 'lo']