Strings
Strings are sequences of characters enclosed in quotes.
(', " , ''' for multi-line strings)
print("Hello, World!") # Output: Hello, World!
Concatenation
String concatenation or joining
fn = "Marwa"
ln = "Abubaker"
full_name = fn + " " + ln
print(full_name)
Type Conversion/Casting
print(type(int(str(123))))
# equivalent to
a = str(123)
b = int(a)
c = type(b)
print(c) # Output: <class 'int'>\
Escape Sequences
(\', \", \n newline, \t tab, \ backslash)
weather = "It\'s a lovely day!\nLet\'s go outside.\tEnjoy the sun."
print(weather)
Formatted Strings (f-strings)
F-strings are the preferred way for formatting.
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 computer science we start counting from 0
Indexing and 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)
Strings are immutable; slicing creates new strings.
language[0] = 'J' # This will raise an error
new_language = "J" + language[1:] # Creating a new string
language = "J" + language[1:] # reassigning the variable
print(language) # Output: Jython
Common Functions/Methods used in Strings
Len Function
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