String Methods:
- len(): Returns the length of a string. Here’s an example:
# Using len() to get the length of a string
my_string = "Python Programming"
# Get the length of the string
length = len(my_string)
print("The length of the string is:", length) # Output: 18
- lower(): Converts all characters in a string to lowercase. Here’s an example:
# Using lower() to convert string to lowercase
my_string = "Python Programming"
# Convert the string to lowercase
lowercase_string = my_string.lower()
print("Original string:", my_string) # Output: Python Programming
print("Lowercase string:", lowercase_string) # Output: python programming
- upper(): Converts all characters in a string to uppercase. Here’s an example:
# Using upper() to convert string to uppercase
my_string = "Python Programming"
# Convert the string to uppercase
uppercase_string = my_string.upper()
print("Original string:", my_string) # Output: Python Programming
print("Uppercase string:", uppercase_string) # Output: PYTHON PROGRAMMING
- title(): Capitalizes the first character of each word in a string. Here’s an example:
# Using title() to capitalize the first character of each word
my_string = "python programming is fun"
# Convert the string to title case
title_string = my_string.title()
print("Original string:", my_string) # Output: python programming is fun
print("Title case string:", title_string) # Output: Python Programming Is Fun
- capitalize(): Capitalizes the first character of a string. Here’s an example:
# Using capitalize() to capitalize the first character of a string
my_string = "python programming"
# Capitalize the first character
capitalized_string = my_string.capitalize()
print("Original string:", my_string) # Output: python programming
print("Capitalized string:", capitalized_string) # Output: Python programming
- swapcase(): Swaps the case of all characters in a string. Here’s an example:
# Using swapcase() to swap the case of all characters in a string
my_string = "Python Programming"
# Swap the case of all characters
swapped_string = my_string.swapcase()
print("Original string:", my_string) # Output: Python Programming
print("Swapped case string:", swapped_string) # Output: pYTHON pROGRAMMING
- count(): Returns the number of occurrences of a substring in a string. Here’s an example:
# Using count() to count occurrences of a substring
my_string = "Python programming is fun. Python is easy to learn."
# Count the occurrences of the word "Python"
count_python = my_string.count("Python")
print("Occurrences of 'Python':", count_python) # Output: 2
- find(): Returns the index of the first occurrence of a substring in a string. Here’s an example:
# Using find() to find the index of the first occurrence of a substring
my_string = "Python programming is fun."
# Find the index of the first occurrence of "Python"
index_python = my_string.find("Python")
print("Index of 'Python':", index_python) # Output: 0
- rfind(): Returns the index of the last occurrence of a substring in a string.
# Using rfind() to find the index of the last occurrence of a substring
my_string = "Python programming is fun. Python is easy to learn."
# Find the index of the last occurrence of "Python"
last_index_python = my_string.rfind("Python")
print("Index of the last 'Python':", last_index_python) # Output: 36
10. index(): Like `find()`, but raises a `ValueError` if the substring is not found.
# Using index() to find the index of the first occurrence of a substring
my_string = "Python programming is fun."
# Find the index of the first occurrence of "Python"
index_python = my_string.index("Python")
print("Index of 'Python':", index_python) # Output: 0
- rindex(): Like `rfind()`, but raises a `ValueError` if the substring is not found.
# Using rindex() to find the index of the last occurrence of a substring
my_string = "Python programming is fun. Python is easy to learn."
# Find the index of the last occurrence of "Python"
last_index_python = my_string.rindex("Python")
print("Index of the last 'Python':", last_index_python) # Output: 36
- startswith(): Returns `True` if a string starts with a specified prefix, otherwise `False`.
# Using startswith() to check if the string starts with a specified prefix
my_string = "Python programming is fun."
# Check if the string starts with "Python"
starts_with_python = my_string.startswith("Python")
print("Starts with 'Python':", starts_with_python) # Output: True
- endswith(): Returns `True` if a string ends with a specified suffix, otherwise `False`.
# Using endswith() to check if the string ends with a specified suffix
my_string = "Python programming is fun."
# Check if the string ends with "fun."
ends_with_fun = my_string.endswith("fun.")
print("Ends with 'fun.':", ends_with_fun) # Output: True
- replace(): Replaces all occurrences of a substring with another substring.
# Using replace() to replace all occurrences of a substring
my_string = "Python is fun. Python is awesome."
# Replace "Python" with "Java"
new_string = my_string.replace("Python", "Java")
print("Original string:", my_string)
print("New string:", new_string)
15. strip(): Removes whitespace (or other characters) from the beginning and end of a string.
str1 = " Python Programming "
# The string method will remove the beginning and ending strings.
result = str1.strip()
print(result)
Output:
Python Programming
- rstrip(): Removes whitespace (or other characters) from the end of a string.
# Using rstrip() to remove trailing whitespace
my_string = "Hello, world! "
# Remove the trailing whitespace
new_string = my_string.rstrip()
print("Original string:", repr(my_string))
print("New string:", repr(new_string))
- lstrip(): Removes whitespace (or other characters) from the beginning of a string.
# Using lstrip() to remove leading whitespace
my_string = " Hello, world!"
# Remove the leading whitespace
new_string = my_string.lstrip()
print("Original string:", repr(my_string))
print("New string:", repr(new_string))
- split(): Splits a string into a list of substrings using a specified delimiter.
# Using split() to split a string into a list of words
my_string = "Python is fun!"
# Split the string by whitespace (default behavior)
words = my_string.split()
print("List of words:", words)
- rsplit(): Splits a string from the right into a list of substrings using a specified delimiter.
# Using rsplit() to split a string from the right
my_string = "Python is fun and Python is awesome"
# Split the string by whitespace from the right
words = my_string.rsplit()
print("List of words:", words)
The separator used is the comma, which is passed as an argument to the rsplit() method. The 1 argument is used to specify that only one splitting should occur, which in this case splits the last fruit from the first two. Finally, we print the list of fruits.
20. join(): Joins a list of strings into a single string using a specified delimiter.
# Joining with a space
words = ["Hello", "world", "Python", "rocks!"]
sentence = " ".join(words)
print(sentence) # Output: "Hello world Python rocks!"
# Joining with a comma
items = ["apple", "banana", "cherry"]
csv_line = ",".join(items)
print(csv_line) # Output: "apple,banana,cherry"
# Joining with a hyphen
letters = ["a", "b", "c", "d"]
hyphenated = "-".join(letters)
print(hyphenated) # Output: "a-b-c-d"
- isalnum(): Returns `True` if a string contains only alphanumeric characters, otherwise `False`.
# String with only letters and numbers
print("Hello123".isalnum()) # Output: True
# String with only letters
print("Python".isalnum()) # Output: True
# String with only numbers
print("2024".isalnum()) # Output: True
# String with a space
print("Hello World".isalnum()) # Output: False
# String with special characters
print("Hello@123".isalnum()) # Output: False
# Empty string
print("".isalnum()) # Output: False
- isalpha(): Returns `True` if a string contains only alphabetic characters, otherwise `False`.
# String with only letters
print("Python".isalpha()) # Output: True
# String with a space
print("Hello World".isalpha()) # Output: False
# String with numbers
print("Python3".isalpha()) # Output: False
# String with special characters
print("Hello!".isalpha()) # Output: False
# Empty string
print("".isalpha()) # Output: False
- isdigit() : Returns `True` if a string contains only digits; otherwise, `False`.
# String with only digits
print("12345".isdigit()) # Output: True
# String with letters
print("123abc".isdigit()) # Output: False
# String with a space
print("123 456".isdigit()) # Output: False
# Empty string
print("".isdigit()) # Output: False
- islower(): Returns `True` if all characters in a string are lowercase, otherwise `False`.
# All lowercase letters
print("hello".islower()) # Output: True
# Mixed case
print("Hello".islower()) # Output: False
# Digits and special characters are ignored
print("hello123!".islower()) # Output: True
# Contains an uppercase letter
print("helloWorld".islower()) # Output: False
# Empty string
print("".islower()) # Output: False
25. isupper(): Returns `True` if all characters in a string are uppercase, otherwise `False`.
# All uppercase letters
print("HELLO".isupper()) # Output: True
# Mixed case
print("Hello".isupper()) # Output: False
# Includes digits and symbols
print("HELLO123!".isupper()) # Output: True
# Contains a lowercase letter
print("HELLOworld".isupper()) # Output: False
# Empty string
print("".isupper()) # Output: False
- istitle(): Returns `True` if a string is titlecased (i.e., the first character of each word is capitalized), otherwise `False`.
# Title-cased string
print("Hello World".istitle()) # Output: True
# Mixed case
print("Hello world".istitle()) # Output: False
# Uppercase string
print("HELLO WORLD".istitle()) # Output: False
# Lowercase string
print("hello world".istitle()) # Output: False
# Single title-cased word
print("Python".istitle()) # Output: True
- isspace(): Returns `True` if a string contains only whitespace characters, otherwise `False`.
# Only spaces
print(" ".isspace()) # Output: True
# Only tabs
print("\t\t".isspace()) # Output: True
# Newline characters
print("\n\n".isspace()) # Output: True
# Mixed whitespace characters
print(" \t\n".isspace()) # Output: True
# Empty string
print("".isspace()) # Output: False
- maketrans(): Creates a translation table to be used with the `translate()` function.
# Mapping characters 'a' -> '1', 'b' -> '2', 'c' -> '3'
trans_table = str.maketrans("abc", "123")
text = "abcde"
print(text.translate(trans_table)) # Output: "123de"
- translate(): Returns a copy of a string with specified characters replaced.
# Create a translation table to replace 'a' -> '1', 'b' -> '2', 'c' -> '3'
trans_table = str.maketrans("abc", "123")
text = "abcde"
print(text.translate(trans_table)) # Output: "123de"
- zfill(): Pads a numeric string with zeros on the left until the specified width is reached.
# Example using zfill() to pad a string with leading zeros
number = "42"
padded_number = number.zfill(5)
print(padded_number) # Output: '00042'
- expandtabs(): Replaces tabs in a string with spaces.
# Example using expandtabs() to replace tabs with spaces
text = "Hello\tWorld\tPython"
expanded_text = text.expandtabs(4) # Replaces tabs with 4 spaces
print(expanded_text)
# Output:
'Hello World Python'
- encode(): Encodes a string using a specified encoding.
# Encoding a string using UTF-8
my_string = "hello world"
encoded_string = my_string.encode("utf-8")
print(encoded_string) # Output: b'hello world'
- format_map(): Formats a string using a dictionary.
# Using format_map() to format a string using a dictionary
person = {"name": "Alice", "age": 30}
# Format string using the dictionary
formatted_string = "My name is {name} and I am {age} years old.".format_map(person)
print(formatted_string)
- isdecimal(): Returns `True` if a string contains only decimal characters, otherwise `False`.
# Using isdecimal() to check if a string contains only decimal characters
my_string = "12345"
# Check if the string contains only decimal characters
is_decimal = my_string.isdecimal()
print(is_decimal) # Output: True
- isnumeric(): Returns `True` if a string contains only numeric characters, otherwise `False`.
# Using isnumeric() to check if a string contains only numeric characters
my_string = "12345"
# Check if the string is numeric
is_numeric = my_string.isnumeric()
print(is_numeric) # Output: True
- partition(): It splits the string into parts based on the first occurrence of the substring.
# Using partition() to split a string based on the first occurrence of a substring
my_string = "Hello, world! Welcome to Python."
# Split the string at the first occurrence of ","
result = my_string.partition(",")
print(result)