This article reviews useful Python string methods for creating new strings without modifying the original, aiding effective string manipulation in projects.
In this article, we review several useful Python string methods that create new strings from a source string without modifying the original. These methods are essential for effective string manipulation in your Python projects and can help you build cleaner and more readable code.
All string methods demonstrated here return new string objects. The original strings remain unchanged throughout the transformations.
The capitalize method converts the first character of the string to uppercase (if it’s alphabetical) and converts all remaining characters to lowercase.Example usage:
The center method returns a new string padded with spaces or an optional specified character. The first parameter represents the total width of the resulting string.Example usage:
The endswith and startswith methods are used to verify whether a string ends or begins with a specified substring, respectively. Both methods return True or False.Example usage:
The find method returns the index of the first occurrence of a substring, and it returns -1 if the substring is not found. You can also specify start and end indices for the search. Conversely, the rfind method searches from the right side of the string.Example usage:
The join method concatenates an iterable of strings using the string on which it is invoked as a separator. Ensure every element in the list is a string.Example usage:
The split method breaks a string into a list of substrings using a specified delimiter. If no delimiter is provided, it splits the string at whitespace.Example usage:
Copy
Ask AI
print('apple kiwi pear'.split())print('apple n kiwi n pear'.split())print('apple kiwi pear'.split('kiwi'))
The lower method converts all uppercase letters in a string to lowercase, while the upper method converts all lowercase letters to uppercase.Example usage for lowercase conversion:
The replace method generates a new string by replacing all occurrences of a specified substring with another substring. You can also limit the number of replacements by providing an optional third parameter.Example usage:
Copy
Ask AI
print('That is great'.replace('great', 'bad'))print('123456789'.replace('123', ''))print('Replace all spaces'.replace(' ', '-'))
The title method capitalizes the first character of every word and converts the rest to lowercase.Example usage:
Copy
Ask AI
print('python has GREAT methods!'.title())
Expected output:
Copy
Ask AI
Python Has Great Methods!
That concludes our comprehensive guide on Python string methods. Start practicing these methods in your coding exercises and projects to improve your string manipulation skills. For more Python tutorials and examples, check out additional Python documentation.