Friday, 31 October 2014

String example in python

from string import lstrip


Str1="Welcome to PythoN"
strReplace="PYTHON"
strFind="Wel-come"

# Get sub-strings from main string..

print "Get first character at index '0': "+ Str1[0]
print "get entire string starting from index 2: "+ Str1[2:]
## Here second parameter is optional. if ignored, it give whole string.
print "get 2 characters from 0 index: "+ Str1[0:2]
print "get first 9 characters: "+ Str1[0:9]
print "get string from index 2-6: "+ Str1[2:9]
##Here first parameter is starting index and the second one is (index-1
print "get first 4 characters: "+ Str1[:4]
##here if first parameter is ignored, it gives 4 characters starting from index 0
print "Last character at index -1: "+ Str1[-1]

#Output:**************************
# Get first character at index '0': W
# get entire string starting from index 2: lcome to PythoN
# get 2 characters from 0 index: We
# get first 9 characters: Welcome t
# get string from index 2-6: lcome t
# get first 4 characters: Welc
# Last character at index -1: N

    #Raw String examples:
r1= r'Hello\\s'
print r1  #o/p: Hello\\s
print 'Hello\\s'    #o/p: Hello\s
print "Hello\s"     #o/p: Hello\s
print "Hello\\s"    #o/p: Hello\s
print "Hello\\\s"   #o/p: Hello\\s

#Triple QUote string:
t1= '''Welcome to Python tutorial..
Python is very simple and easy to learn (\t) programming language. \nPython is used in e-hacking .'''
print t1
## output:**************************
# Welcome to Python tutorial..
# Python is very simple and easy to learn (    ) programming language.
# Python is used in e-hacking .

print "+++++++++++String function eg:+++++++++++++"
s1= "WELcome to PYTHON"
print s1.capitalize() # Welcome to python
print s1.title()    #Welcome To Python
print s1.center(30)#      WELcome to PYTHON    
# count(str, beg= 0,end=len(string))
# Counts how many times str occurs in string or in a substring of string if starting index beg and ending index end are given
print "count of substring 't' in s1: "+ str(s1.count("t"))
print "count of substring 'o' in s1: "+ str(s1.count("o", 0, len(s1)))
print 'Length of the string: ' + str(len(s1)) + '''
and we can also find the length if the string using s1.__len()__: ''' + str(s1.__len__())

print s1.endswith("ON")  #True
print "endswith: "+ str(s1.endswith("ON")) #True
print "endswith: "+ str(s1.endswith("Test")) #False
print "startswith: "+ str(s1.startswith("WEL")) #True
print "startswith: "+ str(s1.startswith("Test")) #False
# Here startswith and endswith returns True or False. Hence convert them b4 appending to a string.

##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# find(str, beg=0 end=len(string))
s1="Venu GOPALA krisHNA"
print s1.find("ALA", 0, len(s1)) #8
print s1.find("GOP")        #5
print "s1.find(\"V\"):-- "+ str(s1.find("V"))   #s1.find("V"):-- 0
if s1.find("Venu")>=0:      #True
    print s1.find("Venu")       #0
print s1.find('kr')     #12
print s1.find('kr', 13, len(s1))    # -1

##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#Length of the string:
print 'length of the string: '+ str(len(s1))
print 'length of string2: '+ str(len('v'))
# we can also find the length of the string using __len__() function.
print "length of the string: "+ str(("Hello").__len__())
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# index(str, beg=0, end=len(string))
# Same as find(), but raises an exception if str not found
s1="Venu GOPALA krisHNA"
print "index of GOPALA: "+ str(s1.index("GOPAL"))  # index of GOPALA: 5
#print "index of a string doesn't exist: "+ str(s1.index("XYZ"))
#Output: ValueError: substring not found ********** ERROR **********
##++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# isalnum() : Returns true if string has at least 1 character and all characters
#  are alphanumeric and false otherwise
S1= "Testing123"
S2= "Python"
S3= "123123123123"
S4= "#$%"
S5= "Venu GOPAL"
print S1.isalnum() #True
print S2.isalnum() #True
print S3.isalnum() #True
print S4.isalnum() #False  due to special characters.
print S5.isalnum() #False due to Space character
print "".isalnum()  #False
##++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
print "isalpha examples: "
# isalpha() :Returns true if string has at least 1 character and all characters are alphabetic and false otherwise
print S1.isalpha() #False
print S2.isalpha() #True
print S3.isalpha() #False
print S4.isalpha() #False  due to special characters.
print S5.isalpha() #False due to Space character
print "".isalpha()  #False
##++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# isdigit() : Returns true if string contains only digits and false otherwise
print "isdigit examples: "
print S1.isdigit() #False
print S2.isdigit() #False
print S3.isdigit() #True
print S4.isdigit() #False  due to special characters.
print S5.isdigit() #False due to Space character
print "".isdigit()  #False
##++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
print "Other String examples: "
print "testing ".isupper()      #False
print "testing 123".islower()   #True
print "TEST".isupper()      #False
print "hello PYthon".upper()    #HELLO PYTHON
print "hello PYTHON".lower()    #hello python
print "Bank of america".title()    #Bank Of America
print "HELLO PYthon".capitalize()   #Hello python
print "HELLO python".swapcase()     #hello PYTHON
##++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# print "123421".isnumeric()
#+++ERROR: AttributeError: 'str' object has no attribute 'isnumeric'
# isnumeric can be used only with unicode string contains only numeric characters
print u"123421".isnumeric() #True
print u"abc".isnumeric()    #False
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
print "".isspace() #False
print " ".isspace() #True
print "\t".isspace() #True
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Strip strings examples:
S1= "   Leading  White Space"
S2="Trailing white Space     "
S3= "    Space at beginning and end of the string    "
print "Length of S1 before lstrip(): "+ str(len(S1))
print "Size of S1 after left Strip: "+ str(len(S1.lstrip()))

# Length of S1 before lstrip(): 23
# Size of S1 after left Strip: 20

print "Length of S2 before lstrip(): "+ str(len(S2))
print "Size of S2 after left Strip: "+ str(len(S2.rstrip()))
# Length of S2 before lstrip(): 25
# Size of S2 after left Strip: 20

print "Length of S3 before lstrip(): "+ str(len(S3))
print "Size of S3 after left Strip: "+ str(len(S3.strip()))
# Length of S3 before lstrip(): 48
# Size of S3 after left Strip: 40

# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
##Replace, Split, Join examples:
# replace(old, new [, max]): Replaces all occurrences of old in string with new or at most max occurrences if max given

S1="Bank of America"
print S1.replace("America", "India")    #Bank of India
# if Old sub string is found, then it replaces with new sub string.
# else, the main string remains the same..
print S1.replace("Maha", "India")   #Bank of America

# split(str="", num=string.count(str))
# Splits string according to delimiter str (space if not provided) and returns list of substrings; split into at
# most num substrings if given

sp1=S1.split(" ")
print sp1   #SP1 is a list
print S1.split("a")  #split by character 'a'

# join(seq) :Merges (concatenates) the string representations of elements in sequence seq into a string, with
# separator string
str = "-";
seq = ("This", "IS", "a Sequence"); # This is sequence of strings.
# sequence -- This is a sequence of the elements to be joined.
print str.join( seq );
print "@".join( seq );

strJoinBy="/"
print strJoinBy.join(sp1)
# Here we can join any list/tuple
print "Length of the string: ", len(S1);  
# Here we don't have to convert to str if we use comma ',''

No comments:

Post a Comment