Lesson 5: Strings
Strings in Python are always defined by 'apostrophes' or "quotation marks".
Strings are made of individual characters. If we want to find the length of a string, we use the len() command:
len("Hello")→ 5len(" ")→ 1 (even a space is a character)len("")→ 0
With the operator in (or not in), we can find out if a string contains a given substring:
"rent" in "Parents"→ True"blue" in "Blueberries"→ False (Case matters)"stick" not in "Computer"→ True
Operations with Strings
String concatenation:
"Los" + "Angeles"→"LosAngeles""New " + "York"→"New York"
String multiplication:
"stone" * 3→"stonestonestone"5 * "pear "→"pear pear pear pear pear "
String indexing:
Each string character is indexed, and by this, we can access them using the [] operator. Indexes in strings start from 0. We can even index from the back using negative numbers.
String: s = "Sharp sword"
String Slicing
String slicing in Python is a technique used to extract a portion (substring) of a string by specifying a start index, a stop index, and an optional step.
The basic syntax is:string[start:stop:step]
- start: The index where the slice begins. If not specified, it starts at index 0 (the start of the string).
- stop: The index where the slice ends. If not specified, it defaults to the end of the string.
- step: The stride or interval between characters. If omitted, it defaults to 1.
Examples:
1. Basic slicing:
text = "Hello, World!"
# Get characters from index 0 up to (but not including) 5
print(text[0:5]) # Output: Hello
# If start is 0, you can omit it
print(text[:5]) # Output: Hello2. Slicing from the middle to the end:
text = "Hello, World!"
# Get characters from index 7 to the end
print(text[7:]) # Output: World!3. Using negative indices:
text = "Python"
# Get the last 3 characters
print(text[-3:]) # Output: hon
# Exclude the last character
print(text[:-1]) # Output: Pytho4. Using step:
text = "123456789"
# Get every second character
print(text[::2]) # Output: 13579
# Reverse a string using a negative step
print(text[::-1]) # Output: 987654321
Want XP, levels and progress tracking? Play this lesson in the CodeStart game.
Play Lesson 5