String methods in Python
Strings in Python are sequences of characters. In Python, strings have a variety of built-in methods that allow you to manipulate and work with text data.
Here are some commonly used string methods:
1. upper() method The upper method converts all characters in the string to uppercase.
Syntax string.upper()
Example:
Python
text = "hello world" # Convert to uppercase print(text.upper()) # Output: HELLO WORLD
Special Note: • Does not modify the original string (strings are immutable in Python).
• Returns a new string.
2. lower() method The lower() method converts all characters of a string to lowercase.
Syntax string.lower()
Example:
Python
text = "HELLO WORLD" print(text.lower()) # Output: hello world
Special Note: • Returns a new string.
• Useful for case-insensitive comparisons.
3. title() method The title method converts the first character of each word to uppercase and the rest to lowercase.
Syntax string.title()
Example:
Python
text = "welcome to python programming" print(text.title()) # Output: Welcome To Python Programming
4. capitalize() method The capitalize method capitalizes the first character of the string and makes all other characters lowercase.
Syntax string.capitalize()
Example:
Python
text = "ashish is a good boy. he Loves Swimming." print(text.capitalize()) # Output: Ashish is a good boy. he loves swimming.
Special Note: As string in Python is immutable, so any operation on it returns a new string.
5. replace() method The replace() method replaces all occurrences of a substring with another.
Syntax string.replace(old, new, count)
Example:
Python
text = "I like Java. Java is popular."
print(text.replace("Java", "Python"))
# Output: I like Python. Python is popular. Special Note: • The count parameter limits replacements.
• Returns a new string.
6. split() Method The split method splits the string into a list using a delimiter.
Syntax string.split(separator, maxsplit)
• Separator: We can specify the separator; default separator is any whitespace.
Example: Split a string into a list where each word is a list item.
Python
text = "apple,banana,cherry"
print(text.split(","))
# Output: ['apple', 'banana', 'cherry'] 7. count() method The count method returns the number of occurrences of a substring.
Syntax string.count(substring, start, end)
Example:
Python
text = "banana"
print(text.count("a")) # Output: 3 8. find() method The find() method returns the lowest index of substring (first occurrence).
Syntax string.find(substring, start, end)
Example:
Python
text = "python programming"
print(text.find("pro")) # Output: 7 Special Note: Returns -1 if substring is not found.
9. rfind() method The rfind() method returns the highest index (last occurrence).
Syntax string.rfind(substring, start, end)
Example:
Python
text = "python programming"
print(text.rfind("m")) # Output: 14 Special Note: Returns -1 if substring is not found.
10. swapcase() method The swapcase() method converts uppercase letters to lowercase and lowercase letters to uppercase.
Syntax string.swapcase()
Example:
Python
text = "PyThOn" print(text.swapcase()) # Output: pYtHoN
11. startswith() method The startswith() method checks if a string begins with the specified prefix.
• The prefix can be a string or a tuple of strings.
• Optional arguments start and end let you restrict the search to a slice of the string.
Syntax string.startswith(prefix, start, end)
Example: Basic usage.
Python
filename = "python_programming.txt"
print(filename.startswith("python")) # True Example: Using a tuple of prefixes.
Python
languages = ["python", "java", "csharp", "cpp"]
for lang in languages:
if lang.startswith(("py", "ja")): # tuple of prefixes
print(lang) # prints 'python' and 'java' Example: With start and end parameters.
Python
text = "python programming"
print(text.startswith("program", 7, 18)) # True 12. endswith() method The endswith() method checks if a string ends with the specified suffix.
• The suffix can be a string or a tuple of strings.
• Optional arguments start and end let you restrict the search to a substring.
Syntax string.endswith(suffix, start, end)
Example: Basic usage.
Python
filename = "python_programming.txt"
print(filename.endswith(".txt")) # True Example: Using a tuple of suffixes.
Python
files = ["report.pdf", "data.csv", "script.py", "notes.txt"]
for f in files:
if f.endswith((".csv", ".txt")): # tuple of suffixes
print(f) # prints 'data.csv' and 'notes.txt' Example: With start and end parameters.
Python
text = "learn_python_basics"
print(text.endswith("python", 6, 12)) # True 13. format() method The format method formats a string using placeholders {}.
Syntax string.format(values...)
Example:
Python
name = "Ashish"
age = 29
print("My name is {} and I am {} years old.".format(name, age))
# Output: My name is Ashish and I am 29 years old. 14. join() method The join() method joins elements of an iterable into a single string using the given separator.
Syntax separator.join(iterable)
Example:
Python
fruits = ["apple", "banana", "cherry"]
print(" - ".join(fruits))
# Output: apple - banana - cherry Special Note: Only works with iterables of strings.
15. len() method The len() function returns the number of characters in a string.
• It counts letters, digits, spaces, special symbols, and emojis.
• It does not skip spaces or hidden characters like \n (newline) or \t (tab).
Syntax len(string)
• string → Any valid string (sequence of characters).
Example:
Python
text = "Hello" print(len(text)) # Output: 5
Example: String with Spaces.
Python
text = "Hello World" print(len(text)) # Output: 11 # Includes the space between Hello and World