Unit 3 - Functions and Strings-1
Unit 3 - Functions and Strings-1
str="Welcome to my class"
print(mystr)
print(str)
Output :
TCS : This is my class.
Welcome to my class
Strings :
String Accessing
• We can access each individual character of a string by using
index.
• Each character can be accessed in two ways - from the front, or
from the rear end.
• Left to right- Forward index (Positive index)
• Right to left- Backward index (Negative index)
Strings:
mystr="PYTHON"
Output :
Output:
String Concatenation :
• The word concatenate means to join together.
• Concatenation is the operation of joining two strings together.
• Python Strings can join using the concatenation operator +.
str="Python"
str1="Programming"
str2="!!"
print(str)
print(str1)
print(str2)
str3=str+" "+str1+".."+str2
print(str3)
Python
Programming
!!
Python Programming..!!
String appending:
• Append means to add something at the end. In python you can add one
string at the end of another string using the += operator.
• "Concatenate" joins two specific items together, whereas "append"
adds another string to existing string.
• Ex- s="Py"
s=s+"thon“ or s+="thon“
• Ex.
str="hello:"
name=input("Enter name")
str+=name
print(str)
Multiplication or Repetition :
• To write the same text multiple times, multiplication or
repetition is used.
• Multiplication can be done using operator *.
str= "My Class is Best..."
print(str*3)
Output :
My Class is Best…
My Class is Best…
My Class is Best…
String Slicing :
• A substring of a string is called slice.
• Slicing is a string operation.
• Slicing is used to extract a part of any string based on a start index
and end index.
• The extracted portions of Python strings called substrings.
• In slicing colon : is used. An integer value will appear on either
side of colon.
• You can take subset of string from the original string by using []
operators also known as slicing operators.
String Slicing :
Syntax :
string_name[starting_index : finishing_index : character_iterate]
• String_name is the name of the variable holding the string.
• starting_index is the index of the beginning character which you want in your
sub-string.
• finishing_index is one more than the index of the last character that you want
in your substring.
• character_iterate is how many characters to extract in each jump.
str="Python Programming is very interesting"
• To create an f-string, prefix the string with the letter “ f ”. The string
itself can be formatted in much the same way that you would with
str.format(). F-strings provide a concise and convenient way to embed
python expressions inside string literals for formatting.
• Ex-
name="abc"
print(f"My name is {name}")
String Formatters : Template
• This class is used to create a string template for simpler string
substitutions.
Ex-
from string import Template
str=Template('My name is $name and I am from $city studying in $college
College')
str1=str.substitute(name='ABC', city='Pune', college='SKNCOE’)
print(str1)
•
String Methods and Functions :
• Python provides us with a number of functions that we can
apply on strings or to create strings.
capitalize() :
• This function capitalizes first letter of string.
str ="python programming"
print(str)
print(str.capitalize())
len() :
• The len() function returns the length of a string
str="Python Programming“
print(len(str))
String Methods and Functions :
lower() and upper() :
• These methods return the string in lowercase and uppercase,
respectively.
Ex- str="pYthOn proGramMinG"
print(str.upper())
print(str.lower())
islower() :
• The method islower() return true if the Python string contains
only lower cased character(s) otherwise return false
String Methods and Functions :
isupper() :
• The method isupper() return true if the Python string contains only
upper cased character(s) otherwise return false.
str="pYthOn proGramMinG"
str1="python programming"
str2="PYTHON PROGRAMMING"
print(str.islower())
print(str1.islower())
print(str2.isupper())
String Methods and Functions :
strip() :
• It removes blank spaces from the beginning and end of the
string.
str=" Python Programming "
print(str)
print(str.strip())
String Methods and Functions :
isdigit() :
• Returns True if all characters in a string are digits.
str="Python Programming"
str1="123456789"
print(str.isdigit())
print(str1.isdigit())
String Methods and Functions :
isalpha() :
• Returns True if all characters in a string are characters from an
alphabet.
str ="PythonProgramming"
str1="Python 123456789"
print(str.isalpha())
print(str1.isalpha())
String Methods and Functions :
isspace() :
• Returns True if all characters in a string are spaces.
str =" "
str1="Python 123456789"
print(str.isspace())
print(str1.isspace())
String Methods and Functions :
isalnum() :
• The method isalnum() is used to determine whether the Python
string consists of alphanumeric characters.
print(str.isalnum())
print(str1.isalnum())
String Methods and Functions :
istitle() :
• The method istitle() return true if the string is a title cased.
print(str.istitle())
print(str1.istitle())
print(str2.istitle())
String Methods and Functions :
title() :
• The method title() returns a copy of the string in which first
character of all words of string are capitalized.
String Methods and Functions :
swapcase() :
• The method swapcase() returns a copy of the string in which all
case based character swap their case.
String Methods and Functions :
startswith() :
• It takes a string as an argument, and returns True if the string it is applied
on starts with the string in the argument.
chr(number)
chr(number)
EX-
ch='a'
print(ord(ch))
o/p- 97
Ex-
print(chr(97))
o/p- a
in and not in Operators/ Membership
Operator
• in and not in operator can be used • Ex-
with string to determine whether a
a="Welcome to python“
string is present in another string.
• Ex- 'b' in 'apple’ if "to" in a:
🡪 False print("Found")
• Ex- 'b' not in 'apple’
else:
🡪 True
• Ex- Ex- 'a' in ‘a’
print("Not Found")
🡪True 🡪 Found
• Ex- Python' in 'Python’
🡪 True
Comparing String
• Python allows you to compare strings using relational(or comparison)
operators such as >, < , <=, >= etc.
Iterating string
• String is sequence type(Sequence of character), You can iterate through the string using for loop.
• The for loop executes for every character in str. The loop starts with the first character and
automatically ends when the last character is accessed.
EX-
s="Welcome to Python"
for element in s:
print(element,end="")
Ex-
s="Welcome to python"
for i in range(len(s)):
print(s[i])
Ex-
s="Welcome to python"
for i,ele in enumerate(s):
print(i, ele)
Iterating string
• Iterate string using while loop:
Ex-
s="Welcome to Python"
index=0
while index<len(s):
char=(s[index])
print(char,end='')
index=index+1
The String Module
• The String Module Consist of a number of useful constants, classes,
and functions.
• These function are used to manipulate a string.
• import string
• dir(string)
['Formatter', 'Template', '_ChainMap', '__all__', '__builtins__', '__cached__',
'__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_re',
'_sentinel_dict', '_string', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase',
'capwords', 'digits', 'hexdigits', 'octdigits', 'printable', 'punctuation',
'whitespace’]
The String Module
• To Know details of particular items.
type(string.digits)
<class 'str’>
• import string
• string.digits
'0123456789’
• import string
string.__builtins__.__doc__