Python provides a rich set of built-in functions and methods for performing various operations on strings. Here are some commonly used operations on strings in Python:
- Concatenation: To concatenate two or more strings, use the
+
operator or thejoin()
method.
pythonstr1 = "Hello"
str2 = "World"
result1 = str1 + " " + str2 # using the + operator
result2 = "".join([str1, " ", str2]) # using the join() method
print(result1) # Output: "Hello World"
print(result2) # Output: "Hello World"
- Substring: To extract a substring from a string, use slicing or the
split()
method.
pythonmy_string = "Hello, World!"
substring1 = my_string[0:5] # using slicing
substring2 = my_string.split(",")[0] # using the split() method
print(substring1) # Output: "Hello"
print(substring2) # Output: "Hello"
- Length: To get the length of a string, use the
len()
function.
pythonmy_string = "Hello, World!"
length = len(my_string)
print(length) # Output: 13
- Replace: To replace a substring with another substring, use the
replace()
method.
pythonmy_string = "Hello, World!"
new_string = my_string.replace("World", "Python")
print(new_string) # Output: "Hello, Python!"
- Case conversion: To convert a string to uppercase or lowercase, use the
upper()
andlower()
methods.
pythonmy_string = "Hello, World!"
uppercase = my_string.upper()
lowercase = my_string.lower()
print(uppercase) # Output: "HELLO, WORLD!"
print(lowercase) # Output: "hello, world!"
These are just a few of the many operations that can be performed on strings in Python.