Table of contents

Strings and String Manipulation

Strings are sequences of characters used to store and manipulate text data in Python. This comprehensive guide will cover the basics of strings, various methods for string manipulation, and practical examples to help you understand and work with strings effectively.

Strings in Python are sequences of characters enclosed in single quotes (') or double quotes ("). You can also use triple quotes (''' or """) for multi-line strings.

Example

single_quote_str = 'Hello' double_quote_str = "World" multi_line_str = """This is a multi-line string"""

You can access individual characters in a string using indexing. Python uses zero-based indexing, so the first character is at index 0.

Example

text = "Hello, World!" print(text[0]) # Output: H print(text[7]) # Output: W print(text[-1]) # Output: !

Slicing allows you to extract a part of a string by specifying a start and end index.

Syntax

substring = string[start:end]

Example

text = "Hello, World!" print(text[0:5]) # Output: Hello print(text[7:12]) # Output: World print(text[:5]) # Output: Hello print(text[7:]) # Output: World! print(text[:]) # Output: Hello, World!

Python provides various built-in methods for string manipulation. Here are some commonly used string methods:

  • upper(): Converts all characters to uppercase.
  • lower(): Converts all characters to lowercase.
  • capitalize(): Capitalizes the first character.
  • title(): Capitalizes the first character of each word.

Example

text = "hello, world!" print(text.upper()) # Output: HELLO, WORLD! print(text.lower()) # Output: hello, world! print(text.capitalize()) # Output: Hello, world! print(text.title()) # Output: Hello, World!
  • strip(): Removes leading and trailing whitespace.
  • lstrip(): Removes leading whitespace.
  • rstrip(): Removes trailing whitespace.

Example

text = " Hello, World! " print(text.strip()) # Output: Hello, World! print(text.lstrip()) # Output: Hello, World! print(text.rstrip()) # Output: Hello, World!
  • find(substring): Returns the index of the first occurrence of the substring.
  • replace(old, new): Replaces all occurrences of old with new.

Example

text = "Hello, World!" print(text.find("World")) # Output: 7 print(text.replace("World", "Python")) # Output: Hello, Python!
  • split(separator): Splits the string into a list of substrings.
  • join(iterable): Joins a list of strings into a single string with the specified separator.

Example

text = "Hello, World!" words = text.split(", ") print(words) # Output: ['Hello', 'World!'] joined_text = ", ".join(words) print(joined_text) # Output: Hello, World!

String formatting allows you to create formatted strings by embedding values within a string template.

name = "Alice" age = 25 text = "My name is %s and I am %d years old." % (name, age) print(text) # Output: My name is Alice and I am 25 years old.
name = "Alice" age = 25 text = "My name is {} and I am {} years old.".format(name, age) print(text) # Output: My name is Alice and I am 25 years old.
name = "Alice" age = 25 text = f"My name is {name} and I am {age} years old." print(text) # Output: My name is Alice and I am 25 years old.

Escape characters are used to include special characters in a string. They are preceded by a backslash (\).

Common Escape Characters

  • \': Single quote
  • \": Double quote
  • \\: Backslash
  • \n: Newline
  • \t: Tab

Example

text = "She said, \"Hello!\"" print(text) # Output: She said, "Hello!" multi_line_text = "First line\nSecond line" print(multi_line_text) # Output: # First line # Second line

Write a program to count the number of vowels in a given string.

def count_vowels(text): vowels = "aeiouAEIOU" count = 0 for char in text: if char in vowels: count += 1 return count input_text = "Hello, World!" print(f"Number of vowels: {count_vowels(input_text)}")

Write a program to check if a given string is a palindrome (reads the same forward and backward).

def is_palindrome(text): cleaned_text = text.replace(" ", "").lower() return cleaned_text == cleaned_text[::-1] input_text = "A man a plan a canal Panama" print(f"Is palindrome: {is_palindrome(input_text)}")

Write a program to count the frequency of each word in a given sentence.

def word_frequency(sentence): words = sentence.split() frequency = {} for word in words: if word in frequency: frequency[word] += 1 else: frequency[word] = 1 return frequency input_sentence = "the quick brown fox jumps over the lazy dog the quick brown fox" print(f"Word frequency: {word_frequency(input_sentence)}")

Write a program to reverse each word in a given sentence.

def reverse_words(sentence): words = sentence.split() reversed_words = [word[::-1] for word in words] return " ".join(reversed_words) input_sentence = "Hello, World!" print(f"Reversed words: {reverse_words(input_sentence)}")

In this guide, we’ve explored the fundamentals of strings and string manipulation in Python, including accessing characters, slicing, common string methods, formatting, and escape characters. Strings are a fundamental data type in Python and mastering their manipulation is essential for any programmer. Practice these concepts with the provided examples and exercises to enhance your understanding and programming skills. In the next section, we will delve into modules and packages, which help you organize and reuse code efficiently. Happy coding!