Operations on Strings in Python
Understanding Operations on Strings
String operations involve various manipulations such as concatenation, reversal, and comparison.
We will explore three different methods to perform operations on strings in Python.
Method 1: Using Standard Library Functions
This method uses built-in string functions for operations.
# Python program for string operations str1 = "Hello" str2 = " World" str1 += str2 print("Concatenated String:", str1) print("Length of String:", len(str1))
Length of String: 11
Method 2: Using Character Array Manipulation
This method manually processes each character for operations.
# Python program to reverse a string str1 = "Hello" char_list = list(str1) left, right = 0, len(char_list) - 1 while left < right: char_list[left], char_list[right] = char_list[right], char_list[left] left += 1 right -= 1 print("Reversed String:", "".join(char_list))
Method 3: Using Pointer Manipulation (Character Comparison)
This method performs operations using character comparison.
# Python program to compare two strings str1 = "Hello" str2 = "Hello" if str1 == str2: print("Strings are equal") else: print("Strings are not equal")