Operations on Strings in Python
Length of a String
You can determine how many characters are in a string using the len()
function.
Example:
fruit = "Mango"
len1 = len(fruit)
print("Mango is a", len1, "letter word.")
Output:
Mango is a 5 letter word.
String as an Array
A string is a sequence of characters, similar to an array. This allows us to access specific characters within the string.
Example:
Copy code
pie = "ApplePie"
print(pie[:5]) # Slicing from Start
print(pie[6]) # Returns character at specified index
Output:
Apple
i
Note: The method of using start and end indices to specify parts of a string is known as slicing.
Loop through a String
Strings are iterable, meaning you can loop through each character in the string.
Example:
alphabets = "ABCDE"
for i in alphabets:
print(i)
Output:
A
B
C
D
E
String Concatenation
You can combine two strings using the + operator.
Example: Merging two city names from Nepal into one string:
city1 = "Kathmandu"
city2 = "Pokhara"
combined_city = city1 + city2
print(combined_city)
Output:
KathmanduPokhara
Example with Space: To add a space between the city names:
city1 = "Kathmandu"
city2 = "Pokhara"
combined_city = city1 + " " + city2
print(combined_city)
Output:
Kathmandu Pokhara