fbpx

Mastering String Manipulation in Python: A Beginner's Guide

Mastering String Manipulation in Python: A Beginner's Guide


INTRODUCTION

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.

Manipulating with strings

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)

    • upper(): Converts a string to uppercase.

 

s = “hello”

print(s.upper())  # Output: HELLO

    • lower(): Converts a string to lowercase.

 

s = “HELLO”

print(s.lower())  # Output: hello

    • strip(): Removes leading and trailing whitespace.

 

s = ”  hello  “

print(s.strip())  # Output: hello

    • replace(old, new): Replaces occurrences of a substring with another substring.

 

s = “Hello, World!”

print(s.replace(“World”, “”))  # Output: Hello, !

    • split(): Splits a string into a list of substrings based on a delimiter.

 

s = “apple,banana,cherry”

print(s.split(“,”))  # Output: [‘apple’, ‘banana’, ‘cherry’]

    • join(): .

 

fruits = [“apple”, “banana”, “cherry”]

print(“, “.join(fruits))  # Output: apple, banana, cherry

    • find(sub):  returnsfirst occurrence of a substring. Returns -1 if not found.

 

s = “hello”

print(s.find(“e”))  # Output: 1

print(s.find(“z”))  # Output: -1

    • count(sub):( no of occurrences of a substring)

 

s = “hello hello”

print(s.count(“hello”)) 

7. String Concatenation: (+ operator).

 

s1 = “Hello”

s2 = “World”

 

8. String Formatting:  provides several ways to format strings:

    • f-strings (formatted string literals): Introduced in  3.6, it allows you to embed expressions inside string literals.

 

name = “Alice”

age = 25

print(f”Name: {name}, Age: {age}”)

    • format() method: Older method, but still commonly used.

 

name = “Bob”

print(“Hello, {}!”.format(name))  # Output: Hello, Bob!

    • String interpolation using % (older style):

 

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)