0% found this document useful (0 votes)
5 views23 pages

Strings

The document provides a comprehensive overview of strings in Python, detailing their definition, creation, initialization, and various operations such as indexing, slicing, and string methods. It explains the immutability of strings, how to traverse them, and demonstrates string manipulation techniques like concatenation, repetition, and membership testing. Additionally, it covers built-in string functions and methods for string analysis and transformation.
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)
5 views23 pages

Strings

The document provides a comprehensive overview of strings in Python, detailing their definition, creation, initialization, and various operations such as indexing, slicing, and string methods. It explains the immutability of strings, how to traverse them, and demonstrates string manipulation techniques like concatenation, repetition, and membership testing. Additionally, it covers built-in string functions and methods for string analysis and transformation.
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/ 23

Strings in Python

● Strings can be defined as a contiguous sequence of symbols or characters.


● In Python Strings are denoted by single, double quotes.

print('spam eggs')# single quotes


print('doesn\'t')# use \' to escape the single
quote...
print("doesn't")# ...or use double quotes instead
print('"Yes," they said.')
print("\"Yes,\" they said.")
print('"Isn\'t," they said.')

Output
spam eggs
doesn't
doesn't
"Yes," they said.
"Yes," they said.
"Isn't," they said.

In the above example, backslash (\) is used as an escape sequence. An


escape sequence is nothing but a special character that has a specific
function. As shown above, backslash (\) is used to escape the quote.

Creating and Initialising Strings

We can inialise a string in the following ways:


● Literal/Constant
strLiteral='spam eggs'
print(strLiteral)
● Using input() method to take input from user

strInput=input()
print(strInput)#hi gets printed

Empty String
word =’’
or
word=””
or
word=str()

Indexing

Strings can be indexed (subscripted), with the first character having index
0. There is no separate character type; a character is simply a string of size
one:

word ='Python'
print(word[0])# character in position 0 output P
print(word[5])# character in position 5 output n

Indices may also be negative numbers, to start counting from the right:

word ='Python'
print(word[-1])# last character n
print(word[-2])# second-last character o
print(word[-6]) P
Python Strings are Immutable

Python strings cannot be changed — they are immutable. Therefore,


assigning to an indexed position in the string results in an error:

word ='Python'
word[0]='J'
TypeError: 'str' object does not support item
assignment

Traversing a string

Traversing a string means accessing all the elements of the string one after
the other by using the subscript. A string can be traversed using a ‘for’ loop
or a ‘while’ loop.

Word =’Python’

# Traversal using for loop
for i in word:
print(i)

Output:
P
y
t
h
o
n

# Traversal using for loop to access index And


character
for i in range(0,len(word):
print(i,’ – ‘,word[i])

Output:
0 - P
1 - y
2 - t
3 - h
4 - o
5 - n


# Traversal using while loop- can access index
and character both
i =0
while i <len(word):
print( word[i])
i = i +1

P
y
t
h
o
n
Multiline Strings/Docstrings
To output the string on multiple lines

To initialize the string on multiple lines.output will be on same line

Or – use ‘’ or “ “ for the same

Operations on String

Concatenation (+)
Strings can be concatenated (glued together) with the + operator. Both the
operands should be of string datatype else it results in an error

word ='uni'+'form' output: uniform


print( word)

num=’12’+’5’ output: 125


print(num)

# Concatenating an integer and a string leads to
an error
word ='un'+3
print( word)

TypeError: can only concatenate str (not "int")
to str

Repetition/Replication (*)

Strings can be repeated with the * operator where one operand is the string
and the other operand is an integer:

word =3*'Python' output: PythonPythonPython


print(word)
word = int(3.5)*’abc’ output: abcabcabc
print(word)

Membership ([not] in)

The in operator returns the boolean value True if the string contains the
given character or the sequence of characters and vice-versa for the case
of not in operator.

word ='crossing farewell'



# Usage of in
In='fare' in word
print(In) Output:True

# Usage of not in
NotIn='Fare' not in word Output:True

Slicing (str[m:n])

● Slicing allows you to obtain a substring


● Slice indices have useful defaults; an omitted first index defaults to zero, an
omitted second index defaults to the length of the string being sliced.

print(word[-len(word):]) #Python
print(word[1:7:2]) #yhn
print(word[::-2]) #nhy
print(word[-6:-1:2]) #Pto

Note:
Slicing rules:
a)if index traverses from LEFT -> RIGHT & STEPVALUE is +ve,it takes
from left to right.If step value is -ve it gives empty string as shown in last 2
examples here
eg) s=’Python’
s[1:5:2] - output: 'yh'
s[:3:1] - output: ‘Pyt’
s[1:5:-1] - ‘’
s[0:5:-2] - ‘’

b)If index traverses from Right – to – Left,the stepvalue is mandatory


& should be negative.If step value is +ve it gives empty string as shown in
last example here
s="python"
s[-1:-6] - ''
s[-1:-6:-1] - 'nohty'
s[-1:-6:-2] - 'nhy'
s[-1:-6:2] - ''

c)If either start or end index is omitted and step value is negative,it
displays the characters in reverse.
Eg1) N="Python Examination"
N[:8:-1] - 'noitanima'
N[8::-1] - 'xE nohtyP'
N[:8:-2] - 'niaia'
N[8::-2] - 'x otP'

d)If the index that is not in range is given in slicing,it does not
generate an error.It gives an EMPTY STRING
s=”Python”
s[100:45:-1] - ‘’
s[10:7] - ‘’
s[7:12] - ‘’

String methods & built in functions


1)len()
Returns the length of the string:

word ='Python'
print(len(word))
6
2)string.capitalize(word)
Return a copy of word with only its first character capitalized and the
remaining characters changed to lowercase.

word ='liGHT battlefield'


print(word.capitalize())
Light battlefield

3)string.find(s, sub[, start[, end]])


Return the lowest index in s where the substring sub is found such that sub
is wholly contained in s[start:end]. Return -1 on failure. Defaults for start
and end and interpretation of negative values is the same as for slices.
4)str.isalnum()
Return true if all characters in the string are alphabets or numeric.Returns
False if there is a space or any other special characters.

5)str.isalpha()
Return true if all characters in the string are alphabetic and there is at least
one character, false otherwise.

word ='apparatus123'
print(word.isalpha())# Returns False as it
contains numeric values

word ='apparatus'
print(word.isalpha())# Returns True
word ='apparatus abc'
print(word.isalpha())# Returns False as it has a
space

6)str.isdigit()
Return true if all characters in the string are digits and there is at least one
character, false otherwise.

word ='displace123'
print(word.isdigit()) False

word ='123'
print(word.isdigit()) True

7)str.lower()
Returns the exact copy of the string with all the letters in lowercase.
word ='fUnCtIonAl jUnGlE'
print(word.lower())
functional jungle

8)str.islower()
Returns True if the string is in lowercase else returns False.
word ='Python'
print(word.islower()) ---- False

word ='python is a prog lang'
print(word.islower()) ----- True

9)str.isupper()
Returns True if the string is in uppercase.
word ='PYTHON'
print(word.isupper()) --- True

word ='python'
print(word.isupper()) --- False

10)str.upper()
Returns the exact copy of the string with all letters in uppercase.

word ='fUnCtIonAl jUnGlE'


print(word.upper())
FUNCTIONAL JUNGLE

11)str.isspace()
Returns True if the string contains only whitespace characters.
Str1=’ abc’
print(Str1.isspace()) -------- False
Str2=’ ‘
print (Str2.isspace()) --------- True
word ='Python'
print(word.isspace()) ---------- False

12)str.lstrip([chars])
Return a copy of the string with leading characters removed. The chars
argument is a string specifying the set of characters to be removed. If
omitted or None, the chars argument defaults to removing whitespace. The
chars argument is not a prefix; rather, all combinations of its values are
stripped

word =' spacious '


print(word.lstrip())# spacious

word ='www.example.com'
print(word.lstrip('www.'))# example.com

13)str.rstrip([chars])
Return a copy of the string with trailing characters removed. The chars
argument is a string specifying the set of characters to be removed. If
omitted or None, the chars argument defaults to removing whitespace. The
chars argument is not a suffix; rather, all combinations of its values are
stripped:

word =' spacious '


print(word.rstrip()) output:' spacious'


word ='mississippi'
print((word.rstrip('ippi')) output:'mississ'

14)strip([chars])- Return a copy of the string with leading and trailing


characters removed.

15)str.istitle()
Return true if the string is a titlecased string and there is at least one
character, for example uppercase characters may only follow uncased
characters and lowercase characters only cased ones. Return false
otherwise.
word ='marsh exact'
print(word.istitle()) ---- False

word ='Marsh Exact'
print(word.istitle())--------- True

16)str.title() converts the string ti titlecase with the first letter of


each word as uppercase and remaining to lowercase

17)str.replace(old, new[, count])

Return a copy of the string with all occurrences of substring old replaced by
new. If the optional argument count is given, only the first count
occurrences are replaced.

word ='mourning silver mourning silver silver


mourning silver'
​print(word.replace('mourning','happy'))# Replaces
all occurrences of mourning
Output:
happy silver happy silver silver happy silver

print(word.replace('mourning','happy',2))#
Replaces only 2 occurence of mourning
Output:
happy silver happy silver silver mourning silver
18)str.join(iterable)

Returns a string in which the string elements have been joined by a


separator.

words =['Jan','Feb','Mar']# List containing three


strings
op ='&'

print(op.join(words))
‘Jan&Feb&Mar’

19)str.swapcase()

Return a copy of the string with uppercase characters converted to


lowercase and vice versa.
word ='fUnCtIonAljUnGlE'
print(word.swapcase())
FuNcTiONaLJuNgLe
20)str.partition(sep)

21)str.split([sep[, maxsplit]])
The function splits the string into substrings using the separator. The
second argument is optional and its default value is zero. If an integer value
N is given for the second argument, the string is split in N+1 strings.

word ='linear$pit$syndrome$cottage$fitness'
​print(word.split('$',3))

Output:
['linear', 'pit', 'syndrome', 'cottage$fitness']
22)count()-It returns the number of times substring occurs in the
given string.If the start index and end index are not given,it starts
from 0 till the length of the string.

23)index()-It is similar to find() as it also searches the


firstoccurance and returns the lowest index of the substring if it is
found.If it is not found in the given string it raises an Exception
24)startswith() – It returns true if the given string starts with the
specified substring,else returns False

25)endswith() – It returns true if the given string ends with the


specified substring,else returns False

26)ord() 27)chr()
2)
Ans:

You might also like