Python Tutorial : Part 9 : Common Python String Methods

Common Python String Methods:  In this tutorial, we will check some popular python String methods and their uses:

  1. capitalize():

It capitalizes the first letter of a python String.

str1 = "hello World !!"
print str1.capitalize()
Output: “Hello World !!”
  1. count (sub_string_name , starting_index, ending_index ) :

This method will check how many time a substring appears in a string within range starting_index and ending_index.

str1 = "hello hello World !!"
subStr1 = "hello"
print str1.count(subStr1,0,len(str1))

The output will be _2 _ 3. endswith(suffix,starting_index,ending_index) :

Find if the string ends with “suffix” within range starting_index and ending_index

str1 = "hello hello World !!"

suffix1 = "!!"
suffix2 = "world"

print str1.endswith(suffix1,0,len(str1))
print str1.endswith(suffix2,0,len(str1))

Output will be True for the first print, and False for the second one.

  1. find(str,starting_index,ending_index):

Find a string ‘str’ inside a string within index range “starting_index” and “ending_index”. Return the index position, if the string is found. Return -1 otherwise.

str1 = "hello World !!"

str2 = "!!"

print str1.find(str2,0,len(str1))

The result will be ’12

  1. isalpha(), isdigit() and isalnum() :

isalpha(): returns True if a python string has all alphabetic characters and it is not empty.It should not contain any space or other characters.

isdigit(): returns True if a python string contains all digits and it is not empty.It should not contain any space or other characters.

isalnum(): returns True if a python string has all alphanumeric characters and it is not empty.It should not contain any space or other characters.

str1 = "abcdefg"
str2 = "1234567"
str3 = "abcd1234"
str4 = ""


print str1.isalpha() #True
print str2.isalpha()
print str3.isalpha()
print str4.isalpha()

print str1.isdigit()
print str2.isdigit() #True
print str3.isdigit()
print str4.isdigit()

print str1.isalnum() #True
print str2.isalnum() #True
print str3.isalnum() #True
print str4.isalnum()
  1. islower() and isupper() :

islower() : Returns True if a string is non-empty and all characters are in lowercase.

isupper() : Returns True if a string is non-empty and all characters are in uppercase.

str1 = "abcdefg"
str2 = "ABCDEF"
str3 = "ABC DEF"

print str1.islower()
print str2.isupper()
print str3.isupper()
print str3.islower()

Output will be:

True
True
True
False
  1. lower() and upper() :_

lower():_ Convert all character of a python string to lowercase_ upper():_ Convert all character of a python string to uppercase

str1 = "Hello World !!"

print str1.upper()
print str1.lower()

output :

HELLO WORLD !!
hello world !!
  1. len(string) ,max(string) , min(string) :
len(string) : Returns the length of a string
max(string) : Returns the max alphabetical character
min(string) : Returns the min alphabetical character 

str1 = "HelloWorld!!"

print len(str1)
print max(str1)
print min(str1)

output : 

12
r
!
  1. lstrip() and rstrip() :

lstrip() : Removes all leading whitespace

rstrip() : Remove all trailing whitespace

str1 = " Hello World "

print "="+str1.lstrip()+"="
print "="+str1.rstrip()+"="

Output :

=Hello World =
= Hello World=
  1. replace( old , new , limit ):

replace a substring ‘old’ with ‘new’. ‘limit’ is optional. It decides how many replacements should be done.

str1 = "new new new new new new new new"
 
print str1.replace('new','old')
print str1.replace('new','old',3)

output :

old old old old old old old old
old old old new new new new new
  1. startswith(sub_string, beginning_index, end_index) :

Return True if a string starts with a substring “sub_string”and the range of index for the string is “beginning_index” and “end_index”.

str1 = "Hello World !!"
 
print str1.startswith("Hello",0,len(str1))

it will return True.

  1. swapcase() and title() :

swapcase() : invert case of all letter in a string.

title() : convert all words start with uppercase.

str1 = "Hello worlD !!"
 
print str1.swapcase()
print str1.title()

Output : 

hELLO WORLd !!
Hello World !!
  1. split() :

Split takes two arguments: First one decides on which separator, the string should be split .The second one decides a maximum number of the split. The second parameter is optional.

It returns a list of all substrings.

str1 = "Hello : World !! : Hello : World"
 
print str1.split()
print str1.split(':')
print str1.split(':',1)

Output will be : 

['Hello', ':', 'World', '!!', ':', 'Hello', ':', 'World']
['Hello ', ' World !! ', ' Hello ', ' World']
['Hello ', ' World !! : Hello : World’]