Strings are the foundation of text manipulation in Python, serving as one of the most versatile and widely used data types. Whether you’re crafting simple text outputs or building complex applications, understanding string operations is essential.
In this guide, we’ll delve into the art of string manipulation, covering everything from basic declarations to advanced techniques like slicing, formatting, and substring extraction. You’ll learn how to harness Python’s built-in string methods, handle immutability, and even solve real-world problems like checking for palindromes or extracting unique substrings.
1. String Declaration: You can declare strings using either single quotes (‘) or double quotes (“).
s1 = ‘Hello’
s2 = “World”
2. Multi-line Strings: For strings that span multiple lines, use triple quotes (”’ or “””).
multiline_string = ”’This is
a multi-line
string”’
3. Accessing Characters: ( individual characters in a string using indexing)
s = “”
print(s[0])
print(s[-1])
4. String Slicing:(extract a substring from a string.)
s = “Hello, World!”
print(s[0:5]) # Output: Hello
print(s[7:]) # Output: World!
print(s[:5]) # Output: Hello
5. String Length🙁 by len() function)
s = “Hello”
print(len(s)) # Output: 5
6. String Methods: (built-in methods)
s = “hello”
print(s.upper()) # Output: HELLO
s = “HELLO”
print(s.lower()) # Output: hello
s = ” hello “
print(s.strip()) # Output: hello
s = “Hello, World!”
print(s.replace(“World”, “”)) # Output: Hello, !
s = “apple,banana,cherry”
print(s.split(“,”)) # Output: [‘apple’, ‘banana’, ‘cherry’]
fruits = [“apple”, “banana”, “cherry”]
print(“, “.join(fruits)) # Output: apple, banana, cherry
s = “hello”
print(s.find(“e”)) # Output: 1
print(s.find(“z”)) # Output: -1
s = “hello hello”
print(s.count(“hello”))
7. String Concatenation: (+ operator).
s1 = “Hello”
s2 = “World”
8. String Formatting: provides several ways to format strings:
name = “Alice”
age = 25
print(f”Name: {name}, Age: {age}”)
name = “Bob”
print(“Hello, {}!”.format(name)) # Output: Hello, Bob!
name = “Charlie”
print(“Hello, %s!” % name) # Output: Hello, Charlie!
9. String Immutability: Since strings are immutable, attempting to change a character in a string will raise an error:
s = “Hello”
s[0] = “h” //TypeError
s = “Hello”
s = “h” + s[1:]
print(s) # Output: hello
Example:whether a string is palindrome or not.
s1=”aba”
s2=s1[::-1]
print(s1==s2)
if s1==s2:
print(“palindrome”)
else:
print(“not a palindrome”)
Program tofind out substring of string
s1=”I love india”
s2=”love”
if s2 in s1:
print(“equal”)
else:
print(“not equal”)
Find the substring of all the strings
s1 =”abcaaabba”
s1=s1.lower()
substring=[]
length=len(s1)
print(length)
for i in range(0,length):
for j in range(i+1,length+1):
substring.append(s1[i:j])
my_set = set(substring)
print(my_set)
Must Read: STM32 ADC: Analog Sensor Reading
Indian Institute of Embedded Systems – IIES