PYTHON – STRING FUNCTIONS
String:
Set of unicode characters
Includes Letters,Numbers, Special Characters or
combination of these types
Representation
with in single / double/triple single/triple double
quotes
ex: ‘apple’ “apple” ‘ ‘apple’’ “““apple”””
‘A140’
Initialization: Syntax: Var_name=‘text’
Ex: Name=“India”
I n d i a
0 1 2 3 5
Accessing : var_name[index]
Str1=“india”
print(str1)
print(str1[3])
print(str1[1:3]
)
String Operations
• Slicing
– Used to access a range of string
– strvar[start:finish-1]
• Ex: print(str1[1:3]
• Concatenation
– Used to combine the strings
– var-=strvar1+strvar2+….+strvarN
• Replication
– Used to repeat a string N number of times
(*)
– Var1=Strvar*N
String Operations
• Escape sequence
– Control characters, not displayed on screen
– Performs specific task
– Used to design the output
– ‘\n’ ‘\a’‘\t’
• Format method
– Used to format / design output
– Syntax: format(value , format specifier)
– Ex:alignment
str1="hai"
print(format(str1,'<20'))
print(format(str1,'>20'))
String Built in Functions
1. len()len(strvar)
Returns No. of chars
2. capitalize()
[Link]()
Capitalize the string (turn first char into upper case)
3. upper() [Link]()
Convert lower case into upper case
4. lower() [Link]()
Convert upper case into lower case
5. title() [Link]()
Convert the string into title case
s1="hai" length=len(s1)
print("\t\t Length is=\t\t",length)
print("\t\tCapital=\t\t",[Link]())
s2="HAI"
print("\t\tLower=\t\t",[Link] ())
print("\t\tUpperr=\t\t",[Link]())
s3="i am an indian"
print("\t\tTitle=\t\t",[Link]())
String Built in Functions
1. isalnum()
[Link]()
returns true if the string contains alphabet,numeric
2. isalpha()
[Link]()
returns true if the string contains only alphabet
3. isdigit()
[Link]()
returns true if the string contains only digits
4. isupper()
[Link]()
returns true if string is in upper case
s1="A130"
s2="apple"
s3="1234"
print("Alnum\t\t=",[Link]())
print("Alnum\t\t=",[Link]())
print("Alpha\t\t=",[Link]())
print("Alpha\t\t=",[Link]())
print("Digit\t\t=",[Link]())
print("Digit\t\t=",[Link]())
String Built in Functions
1. istitle()
[Link](sub(str)
)
returns true if string is
in title case
2. isspace()
[Link]()
returns true if string is
a spaec
Ex:
String Built in Functions
1. count()
[Link](substr)
returns total number of occurences of the given
sub string
2. index()
[Link](sub[start,end])
returns the lowest index of the substring present
in the string (first occurrence)
String Built in Functions
1. endswith()
[Link](substr)
[Link](substr,start,end)
returns a boolean value
True- if strvar ends with the substr
False- otherwise
2. find()
[Link](substr)
returns the lowest index of the substring
(first occurrence)
3. split() [Link](str)
returns the list of all words in the string using str as a
separator
s1="String string String string String"
print([Link]("string"))
print([Link]("String"))
print([Link]("string"))
print([Link]("String",0,27))
print([Link]("String",0,35))
print([Link]("string"))
print([Link](' '))