String Methods

Working on strings in python

Changing the capitalization of a string

Python’s string provides many functions that act on the capitalization of a string. These include:

  • str.upper
  • str.lower
  • str.capitalize
  • str.swapcase

str.upper()

str.upper takes every character in a string and converts it into its uppercase equivalent, for example:

print("TheCleverProgrammer".upper())

#Output
THECLEVERPROGRAMMER

str.lower()

str.lower does the opposite , it takes every character in a string and converts it to its lowercase equivalent:

a = "THEcleverPROGRAmmer"
print(a.lower())

#Output
thecleverprogrammer

str.capitalize()

str.capitalize returns a capitalized version of the string, that is , it makes the first character have upper case and the rest lower:

a = "the CleVer pRogrammer"
print(a.capitalize())

#Output
The clever programmer

str.title()

str.title returns the title cased version of the string, that is every letter in the beginning of a word is made upper case and all others are made lower case:

a = "the CleVer pRogrammer"
print(a.title())

#Output
The Clever Programmer

str.swapcase()

str.swapcase() returns a new string object in which all lower case characters are swapped to upper case and all upper case characters to lower:

a = "the CleVer pRogrammer"
print(a.swapcase())

#Output
THE cLEvER PrOGRAMMER

Striping unwanted characters from a string

Three methods are provided that offer the ability to strip leading and trailing from a string:

  • str.strip()
  • str.rstrip()
  • str.lstrip()

srt.strip()

str.strip acts on a given string and removes any leading or trailing characters contained in the argument characters, if characters is not supplied or is None, all white space characters are removed by default, for example:

print(" the clever programmer ".strip())

#Output
the clever programmer
print(">>> the clever programmer".strip('>'))

#Output
  the clever programmer

str.rstrip() and str.lstrip()

These methods have similar semantics and arguments with str.strip(), their difference lies in the direction from which they start.

str.rstrip() starts from the end of the string while str.lstrip() splits from the start of the string.

for example:

print(">>> the clever programmer >>>".rstrip('>'))

#Output
>>> the clever programmer

print(">>> the clever programmer >>>".lstrip('>'))

#Output
the clever programmer >>>

Previous||Next Chapter

Leave a Reply