NEXAVEDA TECH TRAINING HUB
Python Strings
Slicing Strings
Slicing in Python allows you to extract a portion (substring) of a string by
specifying the start and end indexes. The slicing operation returns characters from
the start index up to, but not including, the end index.
Syntax: string[start:end]
If you omit the start index, it defaults to 0. If you omit the end index, it goes
till the end of the string.
Examples:
text = "Hello, World!"
print(text[0:5]) # Output: Hello
print(text[7:12]) # Output: World
print(text[:5]) # Output: Hello (start is defaulted)
print(text[7:]) # Output: World! (end is defaulted)
Modify Strings:
Modify Strings Although strings in Python are immutable (cannot be
changed), you can create new strings using various string methods.
Common Modifications:
text = " Hello, World! "
print(text.strip()) # Removes whitespace from both ends
print(text.lower()) # Converts the string to lowercase
print(text.upper()) # Converts the string to uppercase
print(text.replace("H", "J")) # Replaces H with J
These methods return new strings with the applied modifications.
String Concatenation:
String Concatenation You can join two or more strings together using
NEXAVEDA TECH TRAINING HUB
the + operator. This is useful when building messages or combining
text.
Example:
first = "Python"
second = "Programming"
result = first + " " + second
print(result) # Output: Python Programming
You can also use the += operator to append strings.
greeting = "Hello"
greeting += " World"
print(greeting) # Output: Hello World
String Methods:
String Methods Python includes many built-in string methods that
help in processing and analyzing text data.
strip()
Removes leading/trailing whitespace
lower()
Converts all characters to lowercase
upper()
Converts all characters to uppercase
replace()
Replaces a specified substring
split()
Splits a string into a list using delimiter
find()
Returns the index of first occurrence
NEXAVEDA TECH TRAINING HUB
count()
Counts the number of occurrences of a substring
startswith()
Checks if string starts with a given value
endswith()
Checks if string ends with a given value
Examples:
text = "hello world"
print(text.upper()) # HELLO WORLD
print(text.find("world")) # 6
print(text.count("l")) # 3
print(text.split()) # ['hello', 'world']