string methods
string methods
1. Strings in Python
A string in Python is a sequence of characters enclosed within single ('), double
(") or triple (''' or """) quotes.
python
string1 = 'Hello'
string2 = "World"
string3 = '''This is a multi-line string.'''
Strings are immutable, meaning they cannot be changed once created.
2. String Methods
Python provides a variety of built-in methods to manipulate strings.
3. String Formatting
Python provides several ways to format strings.
4. String Slicing
Slicing allows extracting specific portions of a string. The syntax is:
string[start:end:step]
start → Index where slicing starts (inclusive).
end → Index where slicing stops (exclusive).
step → Number of steps to take.
A. Basic Slicing
text = "Python"
print(text[0:4]) # 'Pyth'
print(text[:3]) # 'Pyt' (start defaults to 0)
print(text[2:]) # 'thon' (end defaults to last index)
C. Using Step
print(text[::2]) # 'Pto' (every second character)
print(text[::-1]) # 'nohtyP' (reverse the string)
5. Examples Combining Methods, Formatting, and Slicing
quote = "The quick brown fox jumps over the lazy dog"
words = quote.split() # Splitting into words
filtered_words = [word.capitalize() for word in words] # Capitalizing each word
formatted_string = " | ".join(filtered_words) # Joining with a separator
print(formatted_string)
Output:
mathematica
The | Quick | Brown | Fox | Jumps | Over | The | Lazy | Dog
6. Summary
Concept Example
String Methods .upper(), .lower(), .replace(), .split(), .join()
String Formatting f"Hello {name}", "{}".format(value), "%s" % value
String Slicing text[start:end:step], text[::-1] for reversing