Learning Sections show
String slicing and operations in Python are fundamental concepts that allow for manipulation and access to substrings and various transformations.
String Slicing
String slicing allows you to extract parts of a string. The general form is:
substring = string[start:stop:step]
start: The starting index of the slice (inclusive).
stop: The ending index of the slice (exclusive).
step: The step size or interval between indices.
1. Basic Slicing:
s = "Hello, World!"
print(s[0:5]) # Output: Hello
2. Strings with Negative Index
print(s[-6:]) # Output: World!
print(s[:-7]) # Output: Hello,
Common String Operations
1. Concatenation
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result) # Output: Hello World
2. Repetitions
str1 = "Ha"
result = str1 * 3
print(result) # Output: HaHaHa
3. Membership
print("ell" in s) # Output: True
print("xyz" not in s) # Output: True