0% found this document useful (0 votes)
13 views15 pages

Strings in Python (1) - 231116 - 111357

This document provides an overview of strings in Python, including their definition, creation, and properties such as immutability and indexing. It covers string operations, including concatenation, repetition, membership, and comparison, as well as built-in functions and methods for string manipulation. Additionally, it explains string slicing, joining, and accessing characters using both positive and negative indexing.

Uploaded by

ameershaikh0222
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views15 pages

Strings in Python (1) - 231116 - 111357

This document provides an overview of strings in Python, including their definition, creation, and properties such as immutability and indexing. It covers string operations, including concatenation, repetition, membership, and comparison, as well as built-in functions and methods for string manipulation. Additionally, it explains string slicing, joining, and accessing characters using both positive and negative indexing.

Uploaded by

ameershaikh0222
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

UNIT – 1

STRINGS IN PYTHON

Definition: A sequence of characters enclosed in single, double or triple quotation


marks.
Example:
‘Python’
“Python”
‘‘‘Python”’
“““Python”””
All the above examples are the same.

Creating and Storing Strings: Strings are another basic data type available in Python.
They consist of one or more characters surrounded by matching quotation marks. For
example,
1. >>> single_quote = 'This is a single message'
>>> print(single_quote)
2. >>> double_quote = "Hey it is my book"
>>> print(double_quote)
3. >>> single_char_string = "A"
>>> print(single_char_string)
4. >>> empty_string = ""
>>> print(empty_string)
5. >>> empty_string = ''
>>> print(empty_string)
6. >>> single_within_double_quote = "Opportunities don't happen. You create them."
>>> print(single_within_double_quote)
7. >>> double_within_single_quote = "Why did she call the man 'smart'?"
>>> print(double_within_single_quote)
8. >>> same_quotes = 'I\'ve an idea'
>>> print(same_quotes)
9. >>> triple_quote_string = '''This
… is
… triple
… quote'''
>>> print(triple_quote_string)
10. >>> triple_quote_string
'This \n is\n triple\n quote'
Strings are surrounded by either single ➀ or double quotation marks ➁. To store a
string inside a variable, you just need to assign a string to a variable. In the above code,
all the variables on the left side of the assignment operator are string variables. A single
character is also treated as string ➂. A string does not need to have any characters in it.
Both ''➃ and "" ➄ are valid strings, called empty strings. A string enclosed in double
quotation marks can contain single quotation marks ➅. Likewise, a string enclosed in
single quotation marks can contain double quotation marks ➆. So basically, if one type
of quotation mark surrounds the string, you have to use the other type within it. If you
want to include the same quotation marks within a string as you have used to enclose
the string, then you need to preface the inner quote with a backslash ➇. If you have a
string spanning multiple lines, then it can be included within triple quotes ➈. All white
spaces and newlines used inside the triple quotes are literally reflected in the string ➉.

Basics of String / Strings are Immutable:

 Strings are immutable in python. It means that the contents of the string cannot
be changed after it has been created. An attempt to do this would lead to an
error.
 Each character has its index or can be accessed using its index.
 String in python has two-way index for each location. (0, 1, 2, ..…….
In the forward direction and -1, -2, -3, in the backward direction.)

Example:

0 1 2 3 4 5 6 7
S i n D h i a n
-8 -7 -6 -5 -4 -3 -2 -1

 The index of string in forward direction starts from 0 and in backward


direction starts from -1.
 The size of string is total number of characters present in the string. (If
there are n characters in the string, then last index in forward direction
would be n-1 and last index in backward direction would be –n.)
 Strings are stored each character in contiguous location.
 The character assignment is not supported in string because strings are
immutable.
Example:
str = “sindhian”
str[2] = ‘a’ # it is invalid. Individual letter assignment not allowed in python

The str() function: The str() function returns a string which is considered an informal
nicely printable representation of the given object. The syntax for str() function is,
str(object)
It returns a string version of the object. If the object is not provided, then it returns
an empty string.
1. >>> str(10)
'10'
2. >>> create_string = str()
3. >>> type(create_string)
Here integer type is converted to string type. Notice the single quotes to represent the
string ➀. The create_string is an empty string ➁of type str ➂.

Traversing a String: Access the elements of string, one character at a time.


str = “sindhian”
for ch in str :
print(ch, end= ‘‘)
Output:
sindhian

String Operators:
a. Basic Operators (+, *)
b. Membership Operators ( in, not in)
c. Comparison Operators (==, !=, <, <=, >, >=)
a. Basic Operators: There are two basic operators of strings:
i. String concatenation Operator (+)
ii. String repetition Operator (*)

i. String concatenation Operator: The + operator creates a new string by joining the
two operand strings.
Example:
>>>”Hello”+”Python”

‘HelloPython’
>>>’2’+’7’
’27’
>>>”Python”+”3.6”
‘Python3.6’

Note: You cannot concatenate numbers and strings as operands with +


operator.Example:
>>>7+’4’ # unsupported operand type(s) for
+: 'int' and 'str'It is invalid and generates an
error.
ii. String repetition Operator: It is also known as String replication operator. It
requires two types of operands - a string and an integer number.

Example:
>>>”you” * 3
‘youyouyou’
>>>3*”you”
‘youyouyou’
Note: You cannot have strings as n=both the operands with * operator.
Example:
>>>”you” * “you” # can't multiply sequence by non-int of type 'str'
It is invalid and generates an error.
b. Membership Operators:
in – Returns True if a character or a substring exists in the given string; otherwise
False

not in - Returns True if a character or a substring does not exist in the given string;
otherwise False

Example:
>>> "sin" in "Sindhian"
False
>>> "Sin" in "Sindhian"
True
c. Comparison Operators: These operators compare two strings character by
character according to their ASCII value.

Characters ASCII (Ordinal) Value

‘0’ to ‘9’ 48 to 57
‘A’ to ‘Z’ 65 to 90
‘a’ to ‘z’ 97 to 122
Example:
>>> 'abc'>'abcD'
False
>>> 'ABC'<'abc'
True
>>> 'abcd'>'aBcD'

True
>>> 'aBcD'<='abCd'
True
Finding the Ordinal or Unicode value of a character:

Function Description
ord(<character>) Returns ordinal value of a character
chr(<value>) Returns the corresponding
character
Example:

>>> ord('b') >>> chr(65)


98 ‘A’
Built-In Functions Used on Strings: There are many built-in functions for which a
string can be passed as an argument

For example,
1. >>> count_characters = len ("eskimos")
2. >>> count_characters
7
3. >>> max("axel")
'x'
4. >>> min("sindhian")
'a'
The number of characters in the string "eskimos" ➀ is calculated using len() function
➁. Characters with highest and lowest ASCII value are calculated using max() ➂ and
min() ➃ functions.
Accessing Characters in String by Index Number
Each character in the string occupies a position in the string. Each of the string’s
character corresponds to an index number. The first character is at index 0; the next
character is at index 1, and so on. The length of a string is the number of characters in it.
You can access each character in a string using a subscript operator i.e., a square
bracket. Square brackets are used to perform indexing in a string to get the value at a
specific index or position. This is also called subscript operator. The index breakdown
for the string "be yourself" assigned to word_phrase string variable is shown below:

The syntax for accessing an individual character in a string is as shown below.


string_name[index]
where index is usually in the range of 0 to one less than the length of the string. The
value of index should always be an integer and indicates the character to be accessed.
For example,
1. >>> word_phrase = "be yourself"
2. >>> word_phrase[0]
'b'
3. >>> word_phrase[1]
'e'
4. >>> word_phrase[2]
''
5. >>> word_phrase[3]
'y'
6. >>> word_phrase[10]
'f'
7. >>> word_phrase[11]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
By referring to the index numbers in square bracket, you can access individual
characters in a string. The index number starts with zero corresponding to the first
character in the string ➁. The index number increases by one as we move to access the
next letter to the right of the current letter ➂–➅. The whitespace character between be
and yourself has its own index number, i.e., 2. The last character in the string is
referenced by an index value which is the (size of the string – 1) or (len(string) – 1). If
you try to specify an index number more than the number of characters in the string,
then it results in IndexError: string index out of range error ➆.
Negative Indexing:
We can also access individual characters in a string using negative indexing. If you have
a long string and want to access end characters in the string, then you can count
backward from the end of the string starting from an index number of −1. The negative
index breakdown for the string “be yourself” assigned to word_phrase string variable is
shown below:
1. >>> word_phrase[-1]
'f'
2. >>> word_phrase[-2]
'l'
By using negative index number of −1, you can print the character ‘f’ ➀, the negative
index number of −2 prints the character ‘l’ ➁. You can benefit from using negative
indexing when you want to access characters at the end of a long string.
String Slicing and Joining
The "slice" syntax is a handy way to refer to sub-parts of sequence of characters within
an original string. The syntax for string slicing is,

With string slicing, you can access a sequence of characters by specifying a range of
index numbers separated by a colon. String slicing returns a sequence of characters
beginning at start and extending up to but not including end. The start and end
indexing values have to be integers. String slicing can be done using either positive or
negative indexing.

1. >>> healthy_drink = "green tea"


2. >>> healthy_drink[0:3]
'gre'
3. >>> healthy_drink[:5]
'green'
4. >>> healthy_drink[6:]
'tea'
5. >>> healthy_drink[:]
'green tea'
6. >>> healthy_drink[4:4]
''
7. >>> healthy_drink[6:20]
'tea'
A substring is created when slicing the strings, which is basically a string that already
exists within another string. A substring is any sequence of characters that is contained
in a string. The string "green tea" is assigned to healthy_drink variable ➀ and a
sequence of characters or a substring is extracted from the beginning (0th Index) up to
the third character (2nd Index) ➁. In string slicing, start index value (including) is
where slicing starts and end index value (excluding) is where the slicing ends. If the
start index is omitted, the slicing starts from the first index number (0th Index) up to the
end index (excluding) in the string. In ➂ substring starting from 0th index to 4th index
is printed. If the end index is omitted, slicing starts from the start index and goes up to
the end of the string index. Substring starting from 6th index to the end of the string is
displayed in ➃. If both the start and end index values are omitted then the entire string
is displayed ➄. If the start index is equal to or higher than the end index, then it
results in an empty string ➅. If the end index number is beyond the end of the string,
it stops at the end of the string ➆.
Slicing can also be done using the negative integer numbers.

The negative index can be used to access individual characters in a string. Negative
indexing starts with −1 index corresponding to the last character in the string and then
the index decreases by one as we move to the left.
1. >>> healthy_drink[-3:-1]
'te'
2. >>> healthy_drink[6:-1]
'te'
You need to specify the lowest negative integer number in the start index position when
using negative index numbers as it occurs earlier in the string ➀. You can also combine
positive and negative indexing numbers ➁.
1. Specifying Steps in Slice Operation: In the slice operation, a third argument
called step which is an optional can be specified along with the start and end index
numbers. This step refers to the number of characters that can be skipped after the start
indexing character in the string. The default value of step is one. In the previous slicing
examples, step is not specified and in its absence, a default value of one is used. For
example,
1. >>> newspaper = "new york times"
2. >>> newspaper[0:12:4]
'ny'
3. >>> newspaper[::4]
In ➁ the slice [0:12:4] takes the character at 0th index which is n and will print every
4th character in the string extending till the 12th character (excluding). You can omit
both start and end index values to consider the entire range of characters in the string by
specifying two colons while considering the step argument which will specify the
number of characters to skip ➂.
2. Joining Strings Using join() Method
Strings can be joined with the join() string. The join() method provides a flexible way to
concatenate strings. The syntax of join() method is,
string_name.join(sequence)
Here sequence can be string or list. If the sequence is a string, then join() function
inserts string_name between each character of the string sequence and returns the
concatenated string. If the sequence is a list, then join() function inserts string_name
between each item of list sequence and returns the concatenated string. It should be
noted that all the items in the list should be of string type.
1. >>> date_of_birth = ["17", "09", "1980"]
2. >>> ":".join(date_of_birth)
'17:09:1980'
3. >>> social_app = ["instagram", "is", "an", "photo", "sharing", "application"]
4. >>> " ".join(social_app)
'instagram is an photo sharing application'
5. >>> numbers = "123"
6. >>> characters = "amy"
7. >>> password = numbers.join(characters)
8. >>> password
'a123m123y'
All the items in the list date_of_birth list variable is of string type ➀. In ➁ the string ":"
is inserted between each list item and the concatenated string is displayed. In social_app
list variable, all the list items are of string type ➂. In ➃, the join() method ensures a
blank space is inserted between each of the list items in social_app and the concatenated
string is displayed. The variables numbers ➄ and characters ➅ are of string type. The
string value of "123" is placed between each character of "amy" string resulting in
'a123m123y'. The string value of "123" is inserted between a and m and again between
m and y and is assigned to password string variable.
String Methods: We can get a list of all the methods associated with string by passing
the str function to dir().
1. >>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__',
'__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__
mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__',
'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format',
'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower',
'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip',
'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip',
'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
Various methods associated with str are displayed ➀.
Built-in functions of string:Example:
str=”data structure”
s1= “hello365”

s2= “python”
s3 = ‘4567’
s4 = ‘ ‘
s5= ‘comp34%@’

S. No. Function Description Example


1 len( ) Returns the length of a string >>>print(len(str))
14
2 capitalize( ) Returns a string with its >>> str.capitalize()
first character capitalized. 'Data structure'
3 find(sub,start,end) Returns the lowest index in the >>> str.find("ruct",5,13)
string where thesubstring sub is 7
found within the slice range. >>> str.find("ruct",8,13)
Returns -1 if sub is not found. -1
4 isalnum( ) Returns True if the characters in >>>s1.isalnum( )
the string arealphabets or True
numbers. False otherwise >>>s2.isalnum( )
True
>>>s3.isalnum( )
True
>>>s4.isalnum( )
False
>>>s5.isalnum( )
False
5 isalpha( ) Returns True if all characters in >>>s1.isalpha( )
the string arealphabetic. False False
otherwise. >>>s2.isalpha( )
True
>>>s3.isalpha( )
False
>>>s4.isalpha( )
False
>>>s5.isalpha( )
False
6 isdigit( ) Returns True if all the characters >>>s1.isdigit( )
in the string aredigits. False False
otherwise. >>>s2.isdigit( )
False
>>>s3.isdigit( )
True
>>>s4.isdigit( )
False
>>>s5.isdigit( )
False
7 islower( ) Returns True if all the characters >>> s1.islower()
in the string arelowercase. False True
otherwise. >>> s2.islower()
True
>>> s3.islower()
False
>>> s4.islower()
False
>>> s5.islower()
True
8 isupper( ) Returns True if all the characters >>> s1.isupper()
in the string areuppercase. False False
otherwise. >>> s2.isupper()
False
>>> s3.isupper()
False
>>> s4.isupper()
False
>>> s5.isupper()
False
9 isspace( ) Returns True if there are >>> " ".isspace()True
only whitespace >>> "".isspace()
characters in the string. False False
otherwise.
10 lower( ) Converts a string in lowercase >>> "HeLlo".lower()
characters. 'hello'
11 upper( ) Converts a string in uppercase >>> "hello".upper()
characters. 'HELLO'
12 lstrip( ) Returns a string after >>> str="data structure"
removing the leading characters. >>> str.lstrip('dat')
(Left side). ' structure'
if used without any argument, it >>> str.lstrip('data')
removes the leading whitespaces. ' structure'
>>> str.lstrip('at')
'data structure'
>>> str.lstrip('adt')
' structure'
>>> str.lstrip('tad')
' structure'
13 rstrip( ) Returns a string after >>> str.rstrip('ure')
removing the trailingcharacters. 'data struct'
(Right side). >>> str.rstrip('rut')
if used without any argument, it 'data structure'
removes the trailing whitespaces. >>> str.rstrip('tucers')
'data '
14 split( ) breaks a string into words and >>> str="Data Structure"
creates a list out of it >>> str.split( )
['Data', 'Structure']
Programs related to Strings:

1. Write a program that takes a string with multiple words and then
capitalize the firstletter of each word and forms a new string out of it.
Solution:

s1=input("Enter a string : ")

length=len(s1)
a=0
end=length
s2="" #empty string
while a<length:
if a==0:
s2=s2+s1[0].upper()

a+=1
elif (s1[a]==' 'and s1[a+1]!=''):
s2=s2+s1[a]
s2=s2+s1[a+1].upper()
a+=2
else:
s2=s2+s1[a]
a+=1
print("Original string : ", s1)
print("Capitalized words string: ", s2)
2. Write a program that reads a string and checks whether it is a
palindrome string ornot.
str=input("Enter a string : ")

n=len(str)
mid=n//2
rev=-1

for i in range(mid):

if str[i]==str[rev]:
i=i+1
rev=rev-1
else:
print("String is not palindrome")
break
print("String is palindrome")

3. Write a program to convert lowercase alphabet into uppercase and vice


versa.
choice=int(input("Press-1 to convert in lowercase\n Press-2 to convert in
uppercase\n"))
str=input("Enter a string: ")
if choice==1:
s1=str.lower()
print(s1)
elif choice==2:
s1=str.upper()
print(s1)
else:
print("Invalid choice entered")

You might also like