
Strings in Python are immutable sequences!
mystr = ‚Welcome to Yabaaa‘
for s in range(len(mystr)):
print(mystr[s] + ‚-‚, end=“) # W-e-l-c-o-m-e- -t-o- -Y-a-b-a-a-a-
string_on_one_line = ‚print it on one line‘
for character in string_on_one_line:
print(character, end=‘ ‚)
print() # p r i n t i t o n o n e l i n e
Strings_on_multiple_lines= “‘Line #1
Line #2“‘
print(len(Strings_on_multiple_lines)) # 15 zählt \n as ++1, “‘ strings on multiple lines “‘
string1 = ‚p‘
string2 = ‚w‘
print(string1 + string2) # pw
print(string2 + string1) # wp
print(5 * string1) # ppppp
print(string2 * 4) # wwww
Finding the ASCII/UNICODE code point value
char1 = ‚g‘ one-character string as its argument
print(ord(char1)) # 103
Vice Versa
print(chr(103)) # g
print(chr(103) == ‚g‘) # True
Python Strings : Slicing, Searching, Immutable
slicing
sentence = „I am a sentence and my purpose is to be a string example!“
print(sentence[:3]) # I a
print(sentence[0:3]) # I a
print(sentence[1:3]) # a
print(sentence[3:]) # m a sentence and my purpose is to be a string example!
print(sentence[3:-2]) # m a sentence and my purpose is to be a string exampl
print(sentence[-3:4]) #
print(sentence[::2]) # Ia etneadm ups st easrn xml!
print(sentence[1::2]) # masnec n yproei ob tigeape
in and not in operator
english_alphabet = ‚abcdef……z‘
print(‚a‘ in english_alphabet) # True
print(‚a‘ not in english_alphabet) # False
Immutable
You can only re-assing the complete str or delete a python string!
Operations like str[index] = ‚a‘, str.append(x), str.instert(0,’a‘) are illegal
Use the List function to transform the python string into a list
mystr = ‚Use list() to transfor str into List.‘
mylist = list(mystr)
print(mylist)
print(mylist.count(„i“)) # 3
print(mystr.count(„i“)) # 3
A list of python string methods are to be found here.
capitalize()
mystr = ‚cApiTalize Me‘
print(‚cApiTalize Me‘.capitalize()) –> # Capitalize me
print(‚cApiTalize Me‘) –> # cApiTalize Me
The original mystr does not change!
.center()
print(‚[‚ + ‚xyzde‚.center(20, ‚*‘) + ‚]‘) –> # [*******xyzde********]
.endswith()
chapter = „Blood Angels“
print(chapter.endswith(„Fists“)) –> # False
print(chapter.endswith(„ngels“)) –> # True
print(chapter.endswith(„Angels“)) –> # True
print(chapter.endswith(„Blood“)) –> # False
str.find()
the_text = ’simple example‘
print(the_text.find(‚ex‘)) –> # 7
the_text = „““Lorem Ipsum is simply dummy text of the printing
and typesetting industry. Lorem Ipsum has been the industry’s
standard dummy text ever since the 1500s, when an unknown printer
took a galley of type and scrambled it to make a type specimen book.
It has survived not only five centuries, but also the leap into electronic
typesetting, remaining essentially unchanged. It was popularised in the
1960s with the release of Letraset sheets containing Lorem Ipsum passages,
and more recently with desktop publishing software like Aldus PageMaker
including versions of Lorem Ipsum.“““
fnd = the_text.find(‚Lorem Ipsum‘)
while fnd != -1:
print(fnd)
fnd = the_text.find(‚Lorem‘, fnd + 1)
str.index(’search for me‘) returns the first occurence and if not in the str then trows an error. find() is safer, does not trow and error and can be used easily.
str.isalnum()
It returns True in case that the python string contains only numbers or only letters and no spaces!
str.isalpha()
Returns True if the str contains only letters! No numbers! No spaces!
str.isdigit()
Returns True if the str contains only numbers! No letters! No spaces!
islower() are all low-case letters , isspace() are all only spaces , isupper() are all only upper-case letters
str.lower()
print(„You can see me NOW!“.lower()) –> # you can see me now!
str.lstrip()
removes all leading spaces
str.rfind()
print(„eat eat sleep eat eat eat sleep eat“.rfind(„sleep“, 3, 15)) –> # 8
str.strip()
omits the leading and trailing white spaces
str.swapcase()
swaps lower with upper and vice versa
str.title()
makes every starting letter of all words upper
str.upper()
makes all upper
the JOIN method
One argument must be a list containing only strings.
print(„separator“.join([„str1 „,“ str2 „,“ str3 „])) –> #str1 separator str2 separator str3
str_list = [‚el one‘,’el two‘,’el three‘,’el four‘]
new_str = „-„.join([‚elOne‘,’elTwo‘,’elThree‘,’elFour‘])
print(new_str) –> # elOne-elTwo-elThree-elFour
the replace() method
print(„The Lunar Wolfes are the best chapter ever!“.replace(„the best chapter ever“, „traitors“))
–> # The Lunar Wolfes are traitors!
the split() method
print(„abc efg\nxyz“.split()) –> # [‚abc‘, ‚efg‘, ‚xyz‘]
Entfernen Sie Doppelte aus Zeichenfolgen
Alle wiederholten Zeichen entfernen (nur das erste Vorkommen behalten, Reihenfolge beibehalten)
text = „balloon“
result = „“.join(dict.fromkeys(text))
print(result) # „balon“
Remove only consecutive duplicates (e.g., „baallooon“ → „balon“)
import itertools
text = „baallooon“
result = „“.join(k for k, _ in itertools.groupby(text))
print(result) # „balon“
Oder ohne itertools:
def remove_consecutive_dupes(s):
out = []
for ch in s:
if not out or ch != out[-1]:
out.append(ch)
return „“.join(out)
print(remove_consecutive_dupes(„baallooon“)) # „balon“
Entfernen Sie Duplikate, ohne die Reihenfolge zu berücksichtigen (nur der eindeutige Satz, die Reihenfolge ist nicht garantiert).
text = „balloon“
result = „“.join(set(text))
print(result) # e.g. „onlab“ (order varies)
There’s no built-in like string.remove_duplicates()
, but use:
"".join(dict.fromkeys(s))
→ keep first occurrence & order.itertools.groupby
or a loop → remove only consecutive duplicates."".join(set(s))
→ get unique characters in any order.
Python String Funktionen
capitalize()
– ändert alle Buchstaben der Zeichenfolge in Großbuchstaben;center()
– zentriert die Zeichenfolge innerhalb des Feldes einer bekannten Länge;count()
– zählt die Vorkommen eines bestimmten Zeichens;join()
– verbindet alle Elemente eines Tupels/einer Liste zu einer Zeichenfolge;lower()
– wandelt alle Buchstaben der Zeichenfolge in Kleinbuchstaben um;lstrip()
– entfernt die weißen Zeichen vom Anfang der Zeichenfolge;replace()
– ersetzt eine gegebene Teilzeichenfolge durch eine andere;rfind()
– findet eine Teilzeichenfolge beginnend am Ende der Zeichenfolge;rstrip()
– entfernt die nachstehenden Leerzeichen vom Ende der Zeichenfolge;split()
– teilt die Zeichenfolge mithilfe eines bestimmten Trennzeichens in eine Teilzeichenfolge auf;strip()
– entfernt die führenden und nachfolgenden Leerzeichen;- str.partition(sep) – Gibt ein 3-Tupel zurück, das den Teil vor dem Trennzeichen, das Trennzeichen selbst und den Teil nach dem Trennzeichen enthält.
swapcase()
– vertauscht die Groß- und Kleinschreibung der Buchstabentitle()
– macht den ersten Buchstaben in jedem Wort groß;upper()
– wandelt alle Buchstaben der Zeichenfolge in Großbuchstaben um.endswith()
–endet die Zeichenfolge mit einer bestimmten Teilzeichenfolge?isalnum()
– besteht die Zeichenfolge nur aus Buchstaben und Ziffern?isalpha()
– besteht die Zeichenfolge nur aus Buchstaben?islower()
– besteht die Zeichenfolge nur aus Kleinbuchstaben?isspace()
– besteht die Zeichenfolge nur aus Leerzeichen?isupper()
– besteht die Zeichenfolge nur aus Großbuchstaben?startswith()
– beginnt die Zeichenfolge mit einer bestimmten Teilzeichenfolge?- sorted() – Nimmt eine Liste und gibt eine neue Liste zurück. Die ursprüngliche Liste bleibt unverändert.
- list.sort() – Wirkt sich auf die Liste selbst aus – es wird keine neue Liste erstellt.
- str() – etwas in einen String konvertiert
- int() / float() – Wenn Sie einen Python-String in einen Int- oder Float-Wert konvertieren möchten, muss der Wert jedoch von diesem Typ sein.