Python String Methods

In this lesson we want to learn about Python String Methods.

 

What is Python String ?

In Python string is a sequence of characters enclosed within single, double or triple quotes. Strings can contain alphanumeric characters, symbols and punctuation marks. They are used to represent text or a combination of characters. In Python, strings are immutable objects, meaning their value cannot be changed once they have been created. The built-in str class in Python provides many methods to manipulate and format strings.

 

Learn More on Python

 

 

Python String Methods

Python has several built in methods for working with strings. these are some of the most commonly used string methods:

  • str.capitalize(): Returns a copy of the string with the first character capitalized.
  • str.center(width, fillchar): Returns a string of specified width, padded with the specified fillchar (or spaces by default) so that the original string is centered.
  • str.count(sub, start, end): Returns the number of non-overlapping occurrences of sub in the string, between the indices start and end.
  • str.endswith(suffix, start, end): Returns True if the string ends with the specified suffix, between the indices start and end.
  • str.find(sub, start, end): Returns the lowest index in the string where sub is found, between the indices start and end. Returns -1 if sub is not found.
  • str.format(*args, **kwargs): Returns a string with placeholders replaced by the specified arguments.
  • str.isalnum(): Returns True if all characters in the string are alphanumeric (letters or digits).
  • str.isalpha(): Returns True if all characters in the string are alphabetical.
  • str.isdigit(): Returns True if all characters in the string are digits.
  • str.islower(): Returns True if all characters in the string are lowercase.
  • str.join(iterable): Concatenates all elements in the iterable into a single string, separated by the original string.
  • str.replace(old, new, count): Returns a copy of the string with all occurrences of old replaced with new. The optional count argument specifies the maximum number of replacements to make.

 

 

This is an example of using some of the string methods:

 

In this example, we define a string message and use several string methods to perform operations on the string. We use the capitalize() method to capitalize the first character of the string, the count() method to count the number of 'l' characters in the string, the endswith()

 

 

 

Run the complete code and this will be the result 

Python String Methods
Python String Methods

 

Leave a Comment