Zeichenfolgen
Strings sind in Anführungszeichen eingeschlossene Zeichenfolgen.
(', " , ''' für mehrzeilige Zeichenfolgen)
print("Hello, World!") # Output: Hello, World!
Verkettung
Zeichenfolgenverkettung oder -verknüpfung
fn = "Marwa"
ln = "Abubaker"
full_name = fn + " " + ln
print(full_name)
Typkonvertierung/Casting
print(type(int(str(123))))
# equivalent to
a = str(123)
b = int(a)
c = type(b)
print(c) # Output: <class 'int'>\
Escape-Sequenzen
(\', \", \n Zeilenumbruch, \t Tab, \ Backslash)
weather = "It\'s a lovely day!\nLet\'s go outside.\tEnjoy the sun."
print(weather)
Formatierte Strings (F-Strings)
F-Strings sind die bevorzugte Formatierungsmethode.
name = "Marwa"
age = 22
print(f'Hello {name}, you are {age} years old.') # F-string
print('Hello ' + name + ', you are ' + str(age) + ' years old.') # concatenated way
print("Hello {}, you are {} years old.".format(name, age)) # .format() method
print('Hello {0}, you are {1} years old.'.format(name, age)) # .format + indexing
In der Informatik beginnen wir mit dem Zählen bei 0
Indizierung und Slicing
language = "Python"
#012345
# [] indexing [start:stop:stepover]
print(language[0]) # Output: P (first character)
print(language[0:3]) # Output: Pyt (characters from index 0 to 2)
print(language[::1]) # Output: Pto (every character)
print(language[-1]) # Output: n (last character)
print(language[:: -1]) # Output: nohtyP (reversed string)
Zeichenfolgen sind unveränderlich; Durch das Schneiden werden neue Zeichenfolgen erstellt.
language[0] = 'J' # Dies führt zu einem Fehler
new_language = "J" + language[1:] # Creating a new string
language = "J" + language[1:] # reassigning the variable
print(language) # Output: Jython
Gemeinsame Funktionen/Methoden, die in Strings verwendet werden
Len-Funktion
print(len(language)) # Output: 6 (length of the string)
quote = 'life is beautiful.'
print(quote.capitalize()) #Output: Life is beautiful. (capitalize first letter)
print(quote.upper()) # Output: LIFE IS BEAUTIFUL. (convert to uppercase)
print(quote.lower()) # Output: life is beautiful. (convert to lowercase)
print(quote.title()) # Output: Life Is Beautiful. (title case)
print(quote.find('is')) # Output: 5 (index of first occurrence of 'is')
print(quote.replace('life', 'Life'))
print(quote) # Original string remains unchanged its immutable