Some useful String Type Built-in Methods in Python with examples

Well, as we do geology, lets first make an example string – “Geology is great” and work on it.

s.capitalize() – Capitalizes the first letter of the string s.

>>> ex.capitalize()
‘Geology is great’
>>> ex[-6:].capitalize()
‘ great’
>>> ex[-5:].capitalize()
‘Great’

s.center(width) Centers the string in the length specified by width. Just try ex.center(100)

s.count(s): Counts the number of occurrences of s in the string

s.endswith() – returns Boolean value

>>> ex.count(‘g’)
2

>>> ex.endswith(‘t’)
True
>>> ex.endswith(‘s’)
False

s.find(): Returns the beginning index in the string

>>> ex.find(‘i’)
8

>>> ex.find(‘x’)
-1

s.index() is similar to s.find(). It would result in a syntax error if the argument is absent.

>>> ex.index(‘i’)
8
>>> ex.index(‘x’)
Traceback (most recent call last):
File “<pyshell#258>”, line 1, in <module>
ex.index(‘x’)
ValueError: substring not found

s.isalnum(): check if the string element is alphanumeric.

>>> ex.isalnum()
False
>>> 22.isalnum()
SyntaxError: invalid syntax
>>> ’22’.isalnum()
True

>>> ‘22.2’.isalnum()
False

>>> ‘22.3abc’.isalnum()
False

isdigit(): Returns true  if all the characters in the string are digits.

>>> ‘22.2’.isdigit()
False
>>> ‘222’.isdigit()
True

islower()-Returns true if all the alphabetic characters in the string are in lowercase

>>> ex.islower()
False

s.isspace() Returns true if there are only whitespace characters in the string

>>> ex.isspace()
False

>>> ” “.isspace()
True

s.isupper(): returns true if string is all uppercase.

>>> ex.isupper()
False
>>> “UPPERCASE”.isupper()
True

s.istitle() Returns true if the string is in title case

>>> ex.istitle()
False
>>> “Man Of Steel”.istitle()
True

 

s.lstrip()/s.rstrip()/s.strip(): use to strip out whitespaces.

Leave a Comment

Your email address will not be published. Required fields are marked *