Basic String Operations with Python

Basic String Operations

Concatenate Strings

Exercise: Concatenate the strings “Hello” and “World” with a space in between.

Solution: 

str1 = "Hello"
str2 = "World"
result = str1 + " " + str2

 Explanation: Use the + operator to concatenate strings and include a space in between.

Repeat a String

Exercise: Repeat the string “Python” 3 times.

Solution: 

result = "Python" * 3

 Explanation: Use the * operator to repeat a string.

Access a Character by Index

Exercise: Get the 4th character from the string “Programming”.

Solution: 

s = "Programming"
char = s[3]

 Explanation: String indexing starts at 0, so the 4th character is at index 3.

Slice a String

Exercise: Get the substring from index 2 to 5 of the string “DataScience”.

Solution: 

s = "DataScience"
substring = s[2:6]

 Explanation: Use slicing to extract a portion of the string.

Find a Substring

Exercise: Find the index of the first occurrence of “code” in “Learn to code with code examples”.

Solution: 

s = "Learn to code with code examples"
index = s.find("code")

 Explanation: Use the find() method to locate the position of a substring.

Count Substring Occurrences

Exercise: Count how many times “is” appears in the string “This is a test. Is it correct?”.

Solution: 

s = "This is a test. Is it correct?"
count = s.lower().count("is")

 Explanation: Use count() to get the number of occurrences. Convert to lowercase to make it case-insensitive.

Check for Substring

Exercise: Check if the string “abc” is present in “abcdefg”.

Solution: 

s = "abcdefg"
contains = "abc" in s

 Explanation: Use the in operator to check for substring presence.

Replace Substring

Exercise: Replace “good” with “bad” in the string “This is a good example.”.

Solution: 

s = "This is a good example."
result = s.replace("good", "bad")

 Explanation: Use replace() to substitute a substring with another.

Uppercase and Lowercase Conversion

Exercise: Convert the string “Hello World” to all uppercase and then all lowercase.

Solution: 

s = "Hello World"
uppercase = s.upper()
lowercase = s.lower()

 Explanation: Use upper() and lower() to change case.

Strip Whitespace

Exercise: Remove leading and trailing whitespace from ” Example “.

Solution: 

s = "   Example   "
stripped = s.strip()

 Explanation: Use strip() to clean up whitespace.

String Formatting

Format Using f-strings

Exercise: Format the string “Hello {name}, you are {age} years old.” with name = “Alice” and age = 30.

Solution: 

name = "Alice"
age = 30
result = f"Hello {name}, you are {age} years old."

 Explanation: Use f-strings for easy string interpolation.

Old-Style Formatting

Exercise: Format the string “Temperature: %d°C” with 25 using old-style formatting.

Solution: 

temp = 25
result = "Temperature: %d°C" % temp

 Explanation: Use % for formatting.

Format with .format()

Exercise: Format the string “Your balance is ${:.2f}” with a balance of 1234.567.

Solution: 

balance = 1234.567
result = "Your balance is ${:.2f}".format(balance)

 Explanation: Use .format() for string formatting with precision.

Named Placeholders

Exercise: Format the string “Name: {name}, Age: {age}” with name = “Bob” and age = 45.

Solution: 

result = "Name: {name}, Age: {age}".format(name="Bob", age=45)

 Explanation: Use named placeholders in .format().

String Alignment

Exercise: Right-align the string “Hello” in a field of width 10.

Solution: 

result = "{:>10}".format("Hello")

 Explanation: Use {:>width} for right alignment.

Padding Strings

Exercise: Pad the string “data” with asterisks on both sides to make it 10 characters wide.

Solution: 

result = "*{:^8}*".format("data")

 Explanation: Use {:^width} for center alignment with padding.

String Methods

Check String Start

Exercise: Check if the string “Hello” starts with “He”.

Solution: 

s = "Hello"
starts = s.startswith("He")

 Explanation: Use startswith() to check the beginning of a string.

Check String End

Exercise: Check if the string “Python” ends with “on”.

Solution: 

s = "Python"
ends = s.endswith("on")

 Explanation: Use endswith() to check the end of a string.

Split a String

Exercise: Split the string “apple,banana,cherry” by commas.

Solution: 

s = "apple,banana,cherry"
parts = s.split(",")

 Explanation: Use split() to divide a string into a list.

Join Strings

Exercise: Join the list [“a”, “b”, “c”] into a single string with hyphens.

Solution: 

parts = ["a", "b", "c"]
result = "-".join(parts)

 Explanation: Use join() to concatenate list elements into a string.

String Length

Exercise: Find the length of the string “Python Programming”.

Solution: 

s = "Python Programming"
length = len(s)

 Explanation: Use len() to determine the number of characters.

String Case Checking

Exercise: Check if the string “Hello World” contains any uppercase letters.

Solution: 

s = "Hello World"
has_upper = any(c.isupper() for c in s)

 Explanation: Use isupper() within a generator expression.

String Compression

Exercise: Convert the string “aaaabbbcccc” to a compressed format “4a3b4c”.

Solution: 

from itertools import groupby
s = "aaaabbbcccc"
compressed = ''.join(f"{len(list(g))}{k}" for k, g in groupby(s))

 Explanation: Use groupby() from itertools to compress repeated characters.

Remove Digits

Exercise: Remove all digits from the string “abc123def456”.

Solution: 

import re
s = "abc123def456"
result = re.sub(r'\d+', '', s)

 Explanation: Use regular expressions to remove digits.

Replace Multiple Substrings

Exercise: Replace “bad” with “good” and “wrong” with “right” in “This is bad and wrong.”.

Solution: 

s = "This is bad and wrong."
result = s.replace("bad", "good").replace("wrong", "right")

 Explanation: Chain replace() methods to handle multiple replacements.

Check for Alphanumeric

Exercise: Check if “abc123” is alphanumeric.

Solution: 

s = "abc123"
is_alphanumeric = s.isalnum()

 Explanation: Use isalnum() to determine if all characters are alphanumeric.

Find All Occurrences

Exercise: Find all starting indices of the substring “is” in “This is a test. Is it correct?”.

Solution: 

s = "This is a test. Is it correct?"
indices = [i for i in range(len(s)) if s.startswith("is", i)]

 Explanation: Use a list comprehension with startswith() to find all occurrences.

Convert to Title Case

Exercise: Convert “hello world” to title case.

Solution: 

s = "hello world"
title_case = s.title()

 Explanation: Use title() to capitalize the first letter of each word.

Convert to Swap Case

Exercise: Convert “Hello World” to swap case (upper becomes lower and vice versa).

Solution: 

s = "Hello World"
swapped_case = s.swapcase()

Explanation: Use swapcase() to swap the case of all characters.

Check if String is Numeric

Exercise: Check if the string “12345” is numeric.

Solution:

s = "12345"
is_numeric = s.isdigit()

Explanation: Use isdigit() to check if the string consists of digits only.

Advanced String Manipulation

Extract Digits

Exercise: Extract all digits from the string “abc123def456”.

Solution: 

import re
s = "abc123def456"
digits = re.findall(r'\d+', s)

Explanation: Use re.findall() to extract all digit sequences.

Remove Punctuation

Exercise: Remove all punctuation from “Hello, world!”.

Solution:

import string
s = "Hello, world!"
result = s.translate(str.maketrans('', '', string.punctuation))

Explanation: Use str.translate() with str.maketrans() to remove punctuation.

Check Palindrome

Exercise: Check if “A man a plan a canal Panama” is a palindrome (ignore spaces and case).

Solution: 

s = "A man a plan a canal Panama"
cleaned = ''.join(c.lower() for c in s if c.isalnum())
is_palindrome = cleaned == cleaned[::-1]

Explanation: Clean the string and check if it reads the same forwards and backwards.

Replace with Regular Expression

Exercise: Replace all sequences of digits in “Price: $1000, $2000” with “XXX”.

Solution: 

import re
s = "Price: $1000, $2000"
result = re.sub(r'\d+', 'XXX', s)

Explanation: Use re.sub() to replace patterns matched by a regular expression.

Extract Email Username

Exercise: Extract the username from the email “user@example.com”.

Solution:

email = "user@example.com"
username = email.split('@')[0]

Explanation: Split the string at ‘@’ and take the first part.

Reverse a String

Exercise: Reverse the string “Hello” to “olleH”.

Solution:

s = "Hello"
reversed_s = s[::-1]

Explanation: Use slicing with [::-1] to reverse the string.

Check String Equality Ignoring Case

Exercise: Check if “hello” is equal to “HELLO” ignoring case.

Solution:

s1 = "hello"
s2 = "HELLO"
equal = s1.lower() == s2.lower()

Explanation: Convert both strings to lowercase before comparison.

Find the Longest Word

Exercise: Find the longest word in the string “I love programming in Python”.

Solution: 

s = "I love programming in Python"
longest_word = max(s.split(), key=len)

 Explanation: Split the string into words and use max() with key=len to find the longest.

Extract File Extension

Exercise: Extract the file extension from the filename “report.pdf”.

Solution: 

filename = "report.pdf"
extension = filename.split('.')[-1]

Explanation: Split the filename by ‘.’ and get the last part.

Remove Specific Characters

Exercise: Remove all occurrences of “a” and “b” from “abracadabra”.

Solution: 

s = "abracadabra"
result = s.translate(str.maketrans('', '', 'ab'))

 Explanation: Use str.translate() with str.maketrans() to remove specific characters.

 

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *

Facebook
Twitter
LinkedIn
WhatsApp
Email
Print