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

Length of text: 13

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

HELLO, WORLD!

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

hello, world!

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

'Hello, World!'

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

Hello, Python!

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

Index of 'World': 7

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

['Hello,', 'World!']

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

Hello World

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

True

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

True

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.