A string literal or string in python can be created using single quotes (' ') , double quotes (" ")
and triple
quotes. When we use triple quotes, strings can span several lines without using the escape character.
For example:
>>> str1 = 'Computer Applications' # String with double quote
>>> str2 = "Applications of computer" # String with single quote
>>> str3 = """Official website
of Python language is:
http://www.python.org/""" # String with triple quote and multiple lines
>>> print (str1, '\n', str2, '\n', str3)
Computer Applications
Applications of computer
Official website
of Python language is:
http://www.python.org/
Accessing String Elements
We can access individual characters using indexing and a range of characters using slicing. Index starts
from 0.
Python indexes the characters in a string from left to right and from right end to left. From left to right,
the first character of a string has the index 0 and from right end to left, the first character of a string is –
1. Individual characters in a string can be accessed by specifying the string name followed by a number in
square brackets ([]).
Let us see a string called ‘COMUTER’ with its index positions:
Index from left 0 1 2 3 4 5 6 7
String/Characters C O M P U T E R
Index from right end –8 –7 –6 –5 –4 –3 –2 –1
For example: For example: For example:
>>> str1 = 'COMPUTER' >>> str1[8] >>> str1[-6]
>>> str1[0] Traceback (most recent call last): 'M'
'C' File "<pyshell#15>", line 1, in <module> >>> str1[-4]
>>> print(str1[7]) str1[8] 'U‘
R IndexError: string index out of range >>> print(str1[-1])
>>> str1[3] R
'P'
Slicing String
A substring of a string is called a slice. Selecting a slice is similar to selecting a character. Subsets of
strings can be taken using the slice operator with two indices in square brackets separated by a colon
([m:n]). The operator [m:n] returns the part of the string from the mth position and up to but not
including position n, i.e., n – 1.
For example:
>>> str1 = "Python in CBSE Schools"
>>> print (str1[0:5]) # prints first five characters, 0-4
Pytho
>>> print (str1[7:15]) # prints 7th position till 15th, i.e., 7-14
in CBSE String indices are zero-
>>> print (str1[-12: ]) # print last 12 characters based. The first
CBSE Schools character in a string
has index 0. This
>>> print (str1[:15]) # Slices 15 characters starting from 0, here we omit applies to both
first index standard indexing and
Python in CBSE slicing.
>>> print (str1[10:]) # Slices 10th position till end, here we omit the last
index
CBSE Schools
>>> print (str1[-12: -1])
?
Try this:
Consider the following string
new_str = “Intellectual Capital"
Write statements in python to implement the following:
(a) To display the last seven characters.
(b) To display the substring starting from index 5 and ending at index 12.
(c) To trim/print the last four characters from the string.
(d) To trim/print the first four characters from the string.
Strings are Immutable
This means that elements of a string object cannot be changed once it has been assigned. But we can
simply reassign different strings to the same name.
For example:
>>> str1 = "Python in CBSE Schools"
>>> str1[0] = 'M'
Traceback (most recent call last):
File "<pyshell#47>", line 1, in <module>
str1[0] = 'M'
TypeError: 'str' object does not support item assignment
But we can reassign:
>>> str1 = "My"+str1 # This is just simply concatenate two strings
>>> str1
'MyPython in CBSE Schools'
Concatenating & Replicating String
Concatenation means joining two operands by linking them end-to-end. In string concatenation, +
operator concatenation two quoted strings with each other and produce a third string.
For example: first second First+second
>>> first = 'One'
>>> second = 'Two' One + Two = OneTwo
>>> first+second
'OneTwo'
>>> one = '1'
>>> two = '2'
>>> print (one+two) If str1 is: "Python in CBSE Schools"
? What will be the output of the two lines:
>>> print (one+2) >>> str1[:4] + str1[4:]
? ?
>>> print (int(one)+int(two))
?
String can be replicated, repeated or repeatedly concatenated with the asterisk operator "*".
For example:
>>> strA = 'Python' strA strA*2
>>> strA*2 Python *2 = PythonPython
'PythonPython‘
>>> print('=' * 30)
==============================
Programming examples (Iterating):
Write a program to enter a string and print the string characters using for loop.
str1 = input("Enter a string: ") Output:
for i in str1: Enter a string: Computer Applications
Computer Applications
print (i, end =' ')
Write a program to enter your name and print it N times (Where N is no. of
characters n your name)
Output:
str1 = input("Enter a string: ") Enter a string: Alex
for i in str1: Alex
Alex
print (str1)
Alex
Alex
Write a program to count total number of characters in an input string.
str1 = input("Enter a string: ") Output:
count = 0 Enter a string: HELPS HEAL WITHOUT HURTING
Total number of characters: 26
for ctr in str1 :
count+=1
print ("Total number of characters: ", count)
Using Membership Operators with String
The membership operators are used to test whether a value is found in a sequence (string, list, tuple,
set and dictionary). There are two types of membership operators.
Operator Description
in This operator tests if one string is present in another string. If a string
exists then it produces True, otherwise False.
For example,
>>> str1 = "Python in CBSE Schools"
>>> 'C' in str1 # returns: True
>>> 'CBSE' in str1 # returns: True
>>> 'cbse' in str7 # returns: False
not in The not in operator evaluates True if it does not find a variable in the
specified sequence, otherwise False.
For example,
>>> 'C' not in str1 # returns: False
>>> 'CBSE' not in str1 # returns: False
>>> 'Help' not in str1 # returns: True
Comparing String
Strings can be compared with the standard operators relational or comparison operators line ==, !=, <,
>, <= and >=. These comparisons use the standard character-by-character comparison rules for ASCII or
Unicode. The comparison operator returns a Boolean result True or False.
Operator Name Example (If Str1 = "Py", Str2 = "Python") Result
== Equal to Str1==Str2 False
!= Not equal to Str1!=Str2 True
> Greater than Str1>Str2 False
< Less than Str1<Str2 True
>= Greater than or equal to Str1>=Str2 False
<= Less than or equal to Str1<=tr2 True
Programming example
Write a program to enter a word and check with the word ‘CBSE’ whether the word comes
after ‘CBSE’ or before ‘CBSE’.
Note. This is similar to the alphabetical order you would use with a dictionary, except that all
the uppercase letters come before all
word = input("Enter any word : ")
if word < "CBSE":
print ("Your word, " + word + ", comes before CBSE.")
elif word > "CBSE":
print ("Your word, " + word + ", comes after CBSE.")
else:
print ("Yes, we have no choice!")
Output:
Enter any word : NCERT
Your word, NCERT, comes after CBSE.
Enter any word : ICSE
Your word, ICSE, comes after CBSE.
Enter any word : BBC
Your word, BBC, comes before CBSE.
String Functions
A string object has a number of functions and methods. The string functions uses a number of
parameters. The dot operator (.) is used along with the string to access string functions except len()
function.
Function Description
len() This method returns the length of the string.
str1 = "Chennai Express“
print(len(str1)) # returns: 15
strip() The strip() method removes any whitespace from the beginning or the end.
lstrip() a=" Hello World " # string has leading and trailing spaces
rstrip() print(a.strip() + 'friends') # returns: hello worldfriends
Note: You can try lstrip() and rstrip() functions to strip leading and trailing spaces
upper() The upper() method converts all the characters of the string into uppercase string.
lower() a = “Hello World“
print (a.upper()) # returns: HELLO WORLD
Note: You can try lower() method to coverts all the characters into lowercase.
replace() This method returns a copy of the string with all the occurrences of old substring replaced by
new substring.
a = "Hello World“
print(a.replace("H", "J")) # returns: Jello World
>>> print(a) # returns: Hello World
Note: The string is immutable so J replaced H for printing in that line only physically string is
not changed.
String function continues….
Function Description
split() This method returns a list of all the words in the string using a separator.
str1 = "Python In CBSE Schools"
print (str1.split(' ')) # returns: ['Python', 'In', 'CBSE', 'Schools']
print (str1.split(' ', 1)) # returns: ['Python', 'In CBSE Schools']
capitalize() This method returns a copy of the string with only its first character capitalized.
str1 = "python in CBSE schools“
print (str1.capitalize()) # returns: Python in cbse schools
istitle() This method checks whether each character in a string start with an upper case letter or not.
str1 = "Python In CBSE Schools“
print (str1.istitle()) # returns: False
str1 = "Python In Cbse Schools“
print (str1.istitle()) # returns: True
ispace() This method checks whether the string consists of whitespace or not.
str1 = " " # only spaces
print (str1.isspace()) # returns: True
str2 = "001-Delhi STD" # mix characters
print (str2.isspace()) # returns: False
Count() This method returns the number of occurrences of a substring inside a string.
str1 = "This is Python string class and this is interesting"
sub = "is"
print ("This string {} occurs: {}".format(sub, str1.count(sub))) # returns: This string is occurs: 4
Programming example
Write a program to enter a string and remove all vowel characters from the string.
string = input("Enter any string: ")
newstr = string; # just create a duplicate copy
vowels = ('a', 'e', 'i', 'o', 'u'); # all vowels
print (string.lower())
for x in string.lower(): # converts into lower case
if x in vowels:
newstr = newstr.replace(x,""); # replace nothing
print("New string after successfully removed all the vowels:");
print(newstr);
Output:
Enter any string: Python in CBSE schools
python in cbse schools
New string after successfully removed all the vowels:
Pythn n CBSE schls
Programming example
Write a program to enter a string and remove all punctuation characters from the following
string.
string = "Hello!!!, he said ---and went."
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
my_str = "Hello!!!, he said ---and went."
# removing punctuation from the string
no_punct = ""
for char in my_str: # iterate each character
if char not in punctuations: # check each character with my_str
no_punct = no_punct + char
print ("String before punctuation:", my_str)
print ("String after punctuation:", no_punct)
Output:
Enter any string: Python in CBSE schools
python in cbse schools
New string after successfully removed all the vowels:
Pythn n CBSE schls