Built-In String Methods and Functions in Python
Python provides a variety of built-in string methods and functions to perform common operations on strings. These methods make it easy to manipulate, format, and query strings in Python.
1. len()
Function
The len()
function returns the length of a string.
Code Example
text = "Hello, World!"
length = len(text)
print("Length of text:", length)
Output
2. upper()
Method
The upper()
method converts all lowercase characters in a string to uppercase.
Code Example
text = "Hello, World!"
uppercase_text = text.upper()
print(uppercase_text)
Output
3. lower()
Method
The lower()
method converts all uppercase characters in a string to lowercase.
Code Example
text = "Hello, World!"
lowercase_text = text.lower()
print(lowercase_text)
Output
4. strip()
Method
The strip()
method removes any leading and trailing whitespace from a string.
Code Example
text = " Hello, World! "
stripped_text = text.strip()
print(f"'{stripped_text}'")
Output
5. replace()
Method
The replace()
method replaces all occurrences of a specified substring with another substring.
Code Example
text = "Hello, World!"
replaced_text = text.replace("World", "Python")
print(replaced_text)
Output
6. find()
Method
The find()
method returns the index of the first occurrence of a specified substring. If the substring is not found, it returns -1.
Code Example
text = "Hello, World!"
index = text.find("World")
print("Index of 'World':", index)
Output
7. split()
Method
The split()
method splits a string into a list of substrings based on a specified delimiter. The default delimiter is whitespace.
Code Example
text = "Hello, World!"
words = text.split()
print(words)
Output
8. join()
Method
The join()
method joins elements of a list (or other iterable) into a single string, with a specified separator.
Code Example
words = ["Hello", "World"]
sentence = " ".join(words)
print(sentence)
Output
9. startswith()
Method
The startswith()
method checks if a string starts with a specified substring. It returns True
or False
.
Code Example
text = "Hello, World!"
print(text.startswith("Hello"))
Output
10. endswith()
Method
The endswith()
method checks if a string ends with a specified substring. It returns True
or False
.
Code Example
text = "Hello, World!"
print(text.endswith("!"))
Output
Conclusion
These built-in string methods and functions allow you to manipulate strings easily and effectively, making them essential for text processing and formatting in Python.