New Batch Starts on 16th Oct.
Module: Network Fundamentals (L2 L3 Protocol Testing)
Timing: 07:00 AM to 08:00 AM IST (Weekdays)
Sign Up Now !

Chapter 7: Working with Strings in Python

Python String Manipulation: Methods and Examples

In Chapter 7, we’ll be looking at how to work with strings in Python. Strings are used everywhere in programming, and Python provides a lot of methods to make string manipulation easy. In this chapter, we’ll explore methods like count(), find(), replace(), and more. We’ll also go through how to slice and concatenate strings, use membership operators, and split or join strings. By the end of this chapter, you should have a good understanding of how to handle strings and apply these concepts in your projects.


Basic String Operations

Explanation:

  • len(a) returns the length of the string, which is 29 characters including spaces.
  • max(a) returns the highest value character in the string based on the ASCII values. In this case, 'y' is the highest valued character.
  • min(a) returns the lowest value character, which in this case is the space character ' ' because spaces have a lower ASCII value than letters.

String Slicing and Concatenation

Explanation:

  • a[0:6] slices the string a from index 0 to 5 (excluding 6), giving us 'python'. Then, we concatenate it with the string ' tutorial' to get 'python tutorial'.
  • The + operator is used to concatenate (join) two strings. For example, 'python' + 'tutorial' results in 'python tutorial'.
  • The * operator repeats the string. a * 3 produces three copies of the string 'python ', resulting in 'python python python'.
  • You can also combine repetition and concatenation in the same expression, as shown with a * 3 + b.

Membership Operators with Strings

Explanation:

  • The expression 't' in a checks if the character 't' exists within the string a, returning True.
  • Similarly, 's' in a checks if 's' is in the string, returning False since the letter 's' is not found in the word 'python'.
  • not in works in reverse: 's' not in a evaluates to True because 's' is not present in the string, and 't' not in a evaluates to False because 't' is present.

Conditional Statements with Strings :

Explanation:
This example shows how to use strings within an ifelse conditional statement. The condition checks if the substring 'up' is found in the string a. If it’s present, the program prints "interface is up". If not, it prints "interface is down". This is particularly useful when checking for certain words in text-based inputs like system logs or commands.

String Methods: count(), find(), and index()

Explanation:

  • count('n') returns the number of occurrences of the character 'n' in the string. In this case, 'n' appears 4 times.
  • find('n') searches for the first occurrence of 'n' in the string and returns its index, which is 5. If the character is not found, it returns -1.
  • index('n') works similarly to find(), but instead of returning -1 when the character is not found, it raises a ValueError.

String Splitting, Joining, and Splitting Lines :

Explanation:

  • split('.') splits the string based on the '.' delimiter, returning a list of segments. This is commonly used for IP addresses.
  • split('n', maxsplit=2) splits the string based on 'n', but only makes 2 splits, resulting in 3 segments.
  • join() joins a list into a string using a specified delimiter. In this example, the '.' character is used to join the elements of the list ['192', '168', '1', '2'].
  • splitlines() splits a string into a list of lines based on line breaks. This is useful for handling multi-line strings.

Stripping Characters: strip(), lstrip(), rstrip() :

Explanation:

  • strip('-') removes all leading and trailing '-' characters from the string.
  • lstrip('-') removes only the leading '-' characters, and rstrip('-') removes only the trailing '-' characters.

String Replacement with replace()

Explanation:

  • replace('n', 'N') replaces every occurrence of the letter 'n' with 'N'.
  • The third argument in replace('n', 'N', 1) limits the number of replacements to just one occurrence.
  • This method is helpful when you need to change specific characters or words in a string.

Case Conversions

Explanation:

  • capitalize() capitalizes only the first letter of the string.
  • title() capitalizes the first letter of each word.
  • upper() converts the entire string to uppercase, and lower() converts it back to lowercase.

Programming Exercises :

  1. Write a Python program to find the number of characters in a string (without using len()).
  2. Write a Python program to count the number of occurrences of all vowels in a string.
  3. Write a Python program to find common characters present in two words.
  4. Write a Python program to check whether a given string is a palindrome.
  5. Write a Python program to convert alternate characters in a string to capital letters.
  6. Write a Python program to read an IP address from stdin and check whether it is valid.
  7. Write a Python program to read a date (dd-mm-yyyy) and print the month name according to the month number.
  8. Write a Python program to reverse a string without using built-in methods.
  9. Write a Python program to count the number of words in a sentence (without using the split() function).
  10. Write a Python program to remove all spaces from a string.
  11. Write a Python program to replace all occurrences of a given character in a string with another character.
  12. Write a Python program to read a sentence and print the longest word in that sentence.
  13. Write a Python program to check if two strings are anagrams (words formed by rearranging the letters of another, like “listen” and “silent”).
  14. Write a Python program to find all the words in a string that start with a vowel.
  15. Write a Python program to read a string and print the ASCII values of each character.
  16. Write a Python program to remove all digits from a given string.
  17. Write a Python program to process the following input data and perform two tasks:
    • 17.1 Count and print the number of interfaces that are “up.”
    • 17.2 Print the names of all interfaces that are “up”.


    We’d love to hear your feedback and suggestions about this article. Feel free to reach out to us using the WhatsApp number below.

    Sajith Achipra has been a trainer and testing consultant at Zframez Technologies since 2009. With 15+ years of experience, he specializes in networking, Python, development, and testing. He conducts online courses to help students and professionals enhance their skills. You can reach him on WhatsApp at +91 8884 884 844 for your training and testing requirements.