how to use python string module

Namaste Friends,



                                     

Today, I am going to show you how to use python string module? and what is some interesting operations of string module can help you? with practical examples?


As We Already Know Python Is Very Easy To Use and  Popularity Of This Programming Language Is Increasing Rapidly. So, If You are new In Python Programming Then Below Links Can Provide You more Valuable Tutorials!





Now, Let's Focus On Main Point And Start With Some basic queries About Python String Module!.

Q 1. What is Python String Module?

Ans. Python String Module is a very useful built-in module, specialized for handling string related operations because this module contains many useful functions, classes, and constants that are also available as the method on strings.


This String Module Provides us Many Extra Capabilities For Handling Strings.


Input : [1]  

#!/usr/bin/python
#
# ============================================
#       PYTHON SHUTIL MODULE TUTORIAL
# ============================================
#
# Author : SSB
#          surajsinghbisht054@gmail.com
#          https://bitforestinfo.blogspot.com
# 
#
# Here, I am Using
# 
# Operating System : Ubuntu 16.04 LTS
# Python Version   : 2.7.12
# Editor           : ipython notebook
#
#

Output : [1]  

  

Input : [2]  

#
# Import module
#
import string

Output : [2]  

  

Input : [3]  

#
# Here, i am going to show you some constants defined in this module.
#
# All ASCII Letters
print "[1 ] ",[string.ascii_letters]
#
# All LowerCase Ascii
print "[2 ] ",[string.ascii_lowercase]
#
# All UpperCase Ascii
print "[3 ] ",[string.ascii_uppercase]
#
# All Digits
print "[4 ] ",[string.digits]
#
# All Hex Digits
print "[5 ] ",[string.hexdigits]
#
# All Letters
print "[6 ] ",[string.letters]
#
# All lower case letters
print "[7 ] ",[string.lowercase]
#
# ALl Punctuation
print "[8 ] ",[string.punctuation]
#
# All Printable Characters
print "[9 ] ",[string.printable]
#
# All Uppercase letters
print "[10] ",[string.uppercase]
#
# All Whitespace
print "[11] ",[string.whitespace]
#
# All Octa Digits
print "[12] ",[string.octdigits]
#
#

Output : [3]  

[1 ]  ['abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ']
[2 ]  ['abcdefghijklmnopqrstuvwxyz']
[3 ]  ['ABCDEFGHIJKLMNOPQRSTUVWXYZ']
[4 ]  ['0123456789']
[5 ]  ['0123456789abcdefABCDEF']
[6 ]  ['ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz']
[7 ]  ['abcdefghijklmnopqrstuvwxyz']
[8 ]  ['!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~']
[9 ]  ['0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c']
[10]  ['ABCDEFGHIJKLMNOPQRSTUVWXYZ']
[11]  ['\t\n\x0b\x0c\r ']
[12]  ['01234567']

Input : [4]  

# Functions
#
#
test_text = "This Is Practical Example of String Module."

#
# Return a copy of word with only its first character capitalized.
print "[1] ", string.capitalize(test_text)
#
# Convert all characters to uppercase.
print "[2] ", string.upper(test_text)
#
# Convert all characters to lowercase
print "[3] ", string.lower(test_text)
#
# Convert all first character of word to uppercase
print "[4] ", string.capwords(test_text)
#
#

Output : [4]  

[1]  This is practical example of string module.
[2]  THIS IS PRACTICAL EXAMPLE OF STRING MODULE.
[3]  this is practical example of string module.
[4]  This Is Practical Example Of String Module.

Input : [5]  

# Now, let me show you some example
# of string character replacing functions
#
#
s = "This Is Practical Example of String Module."
#
# replace old characters with new characters 
print "[1 ] ",string.replace(s, "Practical Example","a tutorial")
#
# replace one set of characters to another more efficiently than
# calling replace functions again and again
#
t = string.maketrans("TIPEoSM", "HHHHHHH")
# Here, i am replacing "TIPEoSM" characters
# with "HHHHHHH" characters.
#
t2 = string.maketrans("TIPEoSM","tipeOsm")
# And Here, I am replacing "TIPEoSM" Characters
# With "tipeOsm" Characters
#
# Print string with t table translation
print "[2 ] ",string.translate(s, t)
#
# print String with t2 table translation
print "[3 ] ",string.translate(s, t2)

Output : [5]  

[1 ]  This Is a tutorial of String Module.
[2 ]  Hhis Hs Hractical Hxample Hf Htring HHdule.
[3 ]  this is practical example Of string mOdule.

Input : [6]  

#
#
#
s = """
This Is Practical Example of String Module.
And \tHere, I am going to show you
some interesting functions of 
String Module In Easyest way!
Let's see.
"""
#
# Here, I am Replacing Tab with 14 whitespace
print "[1 ] ",[string.expandtabs(s, 14)]
#
# This Function Returns provided character lower index 
# number if character found in string else return -1.
#
print "[2 ] ",[string.find(s, 'interesting')]
#
# This Function also Returns provided character lower index 
# number if character found in string else raise error.
#
print "[3 ] ",[string.index(s, "Practical")]
#
#

Output : [6]  

[1 ]  ["\nThis Is Practical Example of String Module.\nAnd           Here, I am going to show you\nsome interesting functions of \nString Module In Easyest way!\nLet's see.\n"]
[2 ]  [84]
[3 ]  [9]

Input : [7]  

#
# Print Example String
#
print s
#
# Count How many time provided character occur in string.
#
print "[1 ] ",string.count(s, "E")
#
#
# Sperate String From Provided Character in list
print "[2 ] ",string.split(s, "I")
#
#
# Join Provided character in all characters of string
print "[3 ] ",string.join(s, "-")
#
#
#

Output : [7]  

This Is Practical Example of String Module.
And  Here, I am going to show you
some interesting functions of 
String Module In Easyest way!
Let's see.

[1 ]  2
[2 ]  ['\nThis ', 's Practical Example of String Module.\nAnd \tHere, ', ' am going to show you\nsome interesting functions of \nString Module ', "n Easyest way!\nLet's see.\n"]
[3 ]  
-T-h-i-s- -I-s- -P-r-a-c-t-i-c-a-l- -E-x-a-m-p-l-e- -o-f- -S-t-r-i-n-g- -M-o-d-u-l-e-.-
-A-n-d- - -H-e-r-e-,- -I- -a-m- -g-o-i-n-g- -t-o- -s-h-o-w- -y-o-u-
-s-o-m-e- -i-n-t-e-r-e-s-t-i-n-g- -f-u-n-c-t-i-o-n-s- -o-f- -
-S-t-r-i-n-g- -M-o-d-u-l-e- -I-n- -E-a-s-y-e-s-t- -w-a-y-!-
-L-e-t-'-s- -s-e-e-.-

Input : [8]  

#
# remove leading character of string from left.
print "[1 ] ",string.lstrip("oThis is my work!.","o")
#
# remove leading character of string from right.
print "[2 ] ",string.rstrip("This is my work!.o","o")
#
# remove leading character of string from left and right both.
print "[3 ] ",string.strip("oThis is my work!.o","o")
#
#

Output : [8]  

[1 ]  This is my work!.
[2 ]  This is my work!.
[3 ]  This is my work!.

Input : [9]  

#
# left-justify provided string in a field of given width
print "[1 ] ",string.ljust("hello", 10,"l")
#
# right-justify provided string in a field of given width
print "[2 ] ",string.rjust("hello", 10,"r")
#
# center-justify provided string in a field of given width
print "[3 ] ",string.center("hello", 10,"c")
#
# let me show you some interesting tricks with these functions
#
# half triangle
for i in range(10):
    print string.ljust("", i,"*")
#
# full triangle
for i in range(0, 20, 2):
    print string.center("*"*i, 20, " ")
#
#

Output : [9]  

[1 ]  hellolllll
[2 ]  rrrrrhello
[3 ]  cchelloccc

*
**
***
****
*****
******
*******
********
*********
                    
         **         
        ****        
       ******       
      ********      
     **********     
    ************    
   **************   
  ****************  
 ****************** 

Input : [10]  

#
# This Function is respectively provide us new features
# of translating characters in string.
# 
print "[1 ] ",'{0} {1} {2} {3} {4}'.format('a', 'p', 'p','l','e')
#
#
print "[2 ] ",'fruit : {}{} {} {} {}'.format('a', 'p', 'p','l','e')
#
#
print "[3 ] ",'{4}, {1}, {3}, {3}, {2}'.format('a', 'p', 'p','l','e')
#
#
print "[4 ] ",'{0} {1}-{2}+{3}*{4}'.format(*"apple") # unpacking all
#
#
print "[5 ] ","Fruits: fruit_1, fruit_2".format(fruit_1="apple", fruit_2="mango")
#
#

Output : [10]  

[1 ]  a p p l e
[2 ]  fruit : ap p l e
[3 ]  e, p, l, l, p
[4 ]  a p-p+l*e
[5 ]  Fruits: fruit_1, fruit_2

Input : [11]  

#
# here, i am showing you some interesting tricks 
# with zip(), and dict() functions
#
# first, create 2 tuple list
t_1 = ("apple","mango","grapes","cherry","banana")
#
# 
t_2 = ("a","m","g","c","b")
#
#
print "[1 ] ",t_1
#
#
print "[2 ] ",t_2
#
# now zip these 2 list into 3rd list
t_3 = zip(t_1, t_2)
#
#
print "[3 ] ",t_3
#
#
t_4= zip(t_2,t_1)
#
#
print "[4 ] ",t_4
#
# and at the end, call dict function
print "[5 ] ",dict(t_3)
#
#
print "[6 ] ",dict(t_4)
#
#

Output : [11]  

[1 ]  ('apple', 'mango', 'grapes', 'cherry', 'banana')
[2 ]  ('a', 'm', 'g', 'c', 'b')
[3 ]  [('apple', 'a'), ('mango', 'm'), ('grapes', 'g'), ('cherry', 'c'), ('banana', 'b')]
[4 ]  [('a', 'apple'), ('m', 'mango'), ('g', 'grapes'), ('c', 'cherry'), ('b', 'banana')]
[5 ]  {'cherry': 'c', 'mango': 'm', 'apple': 'a', 'grapes': 'g', 'banana': 'b'}
[6 ]  {'a': 'apple', 'c': 'cherry', 'b': 'banana', 'm': 'mango', 'g': 'grapes'}

Input : [12]  

#
# string.Template() in some manners also works like 
# string.format() functions but Instead of the normal %-based 
# substitutions, Templates support $-based substitutions.
# and this function also provides some unique features
#
# let me show you small example of string.Template function
#
s = string.Template('Fruit lists : $fruit_1 $fruit_2')
#
# 
print "[1 ] ",s.substitute(fruit_1="apple", fruit_2="mango")
#
#
d = dict(fruit_1="grapes")
#
#
print "[2 ] ",string.Template('Fruit lists : $fruit_1 $fruit_2').safe_substitute(d)
#
#

Output : [12]  

[1 ]  Fruit lists : apple mango
[2 ]  Fruit lists : grapes $fruit_2

You more Valuable Tutorials Check This!










If you like my tutorial,
Then don't forget to subscribe,
comments and share.

By SSB

Have a wonderful day!

Share this

Related Posts

Previous
Next Post »