String operation - II

String Operations in Python (II)

Python provides a rich set of string methods for text manipulation and analysis. Below, we explore key string methods with examples.

1. len() Function

The len() function returns the total number of characters in a string.

Example:

text = "coding"
print(len(text))  # Output: 6

2. upper() and lower() Methods

The upper() method converts all characters in a string to uppercase, while the lower() converts them to lowercase.

Example:

text = "PyThOn"
upper_text = text.upper()
print(upper_text)  # Output: PYTHON

lower_text = upper_text.lower()
print(lower_text)  # Output: python

3. islower() and isupper() Methods

The islower() method checks if all characters in a string are lowercase, returning True or False. The isupper() method checks for uppercase characters.

Example:

str1 = "hello"
str2 = "WORLD"
print(str1.islower())  # Output: True
print(str2.isupper())  # Output: True

4. startswith() and endswith() Methods

The startswith() method checks if a string begins with a specified substring, and endswith() checks if it ends with a specified substring. Both return True or False.

Example:

text = "Python Programming Basics"
print(text.startswith("Python"))        # Output: True
print(text.endswith("Basics"))          # Output: True
print(text.startswith("Program", 7))    # Output: True
print(text.startswith("Basics", 0, 10)) # Output: False

5. split() and join() Methods

The split() method breaks a string into a list of substrings based on a delimiter. The join() method combines a list of strings into a single string using a specified separator.

Example:

text1 = "learn to code"
print(text1.split())  # Output: ['learn', 'to', 'code']

text2 = "apple,banana,orange"
print(text2.split(","))  # Output: ['apple', 'banana', 'orange']

words = ["Python", "is", "awesome"]
print(" ".join(words))   # Output: Python is awesome
print("-".join(words))   # Output: Python-is-awesome

6. strip(), lstrip(), and rstrip() Methods

The strip() method removes specified characters from both ends of a string, lstrip() removes them from the left, and rstrip() removes them from the right.

Example:

text = "===coding==="
print(text.strip("="))   # Output: coding
print(text.lstrip("="))  # Output: coding===
print(text.rstrip("="))  # Output: ===coding

7. find() Method

The find() method returns the lowest index of a substring in a string. If the substring is not found, it returns -1.

Example:

text = "learn python learn"
substring = "learn"
print(text.find(substring))         # Output: 0
print(text.find("java"))            # Output: -1
print(text.find(substring, 5, len(text)))  # Output: 13

👀Note: Unlike the index() method, which raises a ValueError when a substring is not found, find() returns -1.

Popular Posts