Professional Documents
Culture Documents
Valid
Test Case 2
abcde12345
Invalid
Test Case 3
abcd01234r
Invalid
Strings
l Immutable sequence of characters
l A string literal uses quotes
l 'Hello' or "Hello“ or ‘’’Hello’’’
l For strings, + means “concatenate”
l When a string contains numbers, it is still a string
l We can convert numbers in a string into a number
using int()
String Operations
String Operations
String Operations
l Single quotes:Example
'spa"m' Strings
l Double quotes: "spa'm"
l Triple quotes: '''... spam ...''', """... spam ..."""
l Escape sequences: "s\tp\na\0m“
3 (coded in hexadecimal):
>>> s = '\001\002\x03'
>>> s
'\x01\x02\x03'
>>> len(s)
3
l
Backslash in Strings
if Python does not recognize the character after a \ as
l
>>> x
'C:\\py\\code'
>>> len(x)
10
Backslash in Strings
>>> x = "C:\py\code"
>>> x
'C:\\py\\code'
>>> len(x)
10
Check this
s = "C:\new\text.dat“
>>>s
print(s)
s1 = r"C:\new\text.dat“
>>>s1
print(s1)
s2 = "C:\\new\\text.dat“
print(s2)
>>>s2
Opening a File
myfile = open('C:\new\text.dat', 'w') - Error
l
>>> print(path)
l # User-friendly format
C:\new\text.dat
>>> len(path)
l
15
Basic Operations
>>> 'Ni!' * 4
'Ni!Ni!Ni!Ni!‘
>>> print('-' * 80) # 80 dashes, the easy way
>>> myjob = "hacker"
>>> for c in myjob:
print(c, end=' ')
hacker
Basic Operations
>>> for c in myjob:
print(c, end=' ')
hacker
Using ‘in’ Operator in Strings
>>> "k" in myjob
l # Found
True
l
True
l
Counting
lCount the number of ‘a’
Counting
lCount the number of ‘a’
l Example
l word = 'Btechallbranches'
l count = 0
l for letter in word :
l if letter == 'a' :
l count = count + 1
l print count
Indexing and Slicing
l >>> S = 'spam'
l Last character in the string has index -1 and
the one before it has index -2 and so on
Indexing and Slicing
Indexing and Slicing
l Take one letter from a word at a time
l Use square bracket and give the index of the
letter to be extracted
l Indexing can be done either from front or from
end
l >>> S[0], S[−2]
l ('s', 'a')
Slicing
l Take a part of a word
l Square bracket with two arguments with a colon
l First value indicates the starting position of the slice
and second value indicates the stop position of the
slice
l Character at the stop position is not included in the
slice
l >>> S[1:3]
l 'pa’
Slicing
lIf the second number is beyond the end of the string,
it stops at the end
lIf we leave off the first or last number of the slice, it is
assumed to be beginning or end of the string
respectively
ls = ‘spam’
l>>>s[:3]
l‘spa’
l>>>s[1:]
l‘pam’
Properties of Slicing
S[1:3] - fetches items at offsets 1 up to but not including 3.
l
item
top-level copy of S
Extended slicing
l X[I:J:K] - means “extract all the items in X, from
offset I through J−1, by K.”
l Third limit, K, defaults to +1
l If you specify an explicit value it is used to skip
items
l Extraction is reversed when negative value is
given for K-1
l Each time K-1 items are skipped
Extended slicing Examples
l >>> S = 'abcdefghijklmnop'
l >>> S[1:10:2] # Skipping items
l 'bdfhj'
l >>> S[::2]
l 'acegikmo‘
l >>> S = 'hello'
l >>> S[::−1] # Reversing items
l 'olleh'
Extended slicing Examples
l >>> S = 'hello'
l >>> S[::−1] # Reversing items
l 'olleh'
String Conversion Tools
l >>> "42" + 1
l TypeError: Can't convert 'int' object to str
implicitly
l >>> int("42"), str(42) # Convert from/to string
l (42, '42')
l int("42") + 1
l 43
l >>> "42" + str(1)
l '421'
Character code Conversions
l ord () - Convert a single character to its
underlying integer code (e.g., its ASCII byte
value)— this value is used to represent the
corresponding character in memory.
l >>> ord('s')
l 115
Character code Conversions
l chr () – Does inverse of ord
l >>> chr(115)
l 's'
Character code Conversions - Example
l >>> S = '5'
l >>> S = chr(ord(S) + 1)
l >>> S
l '6‘
l >>> S = chr(ord(S) + 1)
l >>> S
l '7'
Character code Conversions - Example
l >>> ord('5') - ord('0')
l 5
l >>> int('1101', 2) # Convert binary to integer
l 13
l >>> bin(13) # Convert integer to binary
l '0b1101'
Concatenation
l >>>S1 = ‘Welcome’
l >>>S2 = ‘Python’
l >>>S3 = S1 + S2
l >>>S3
l 'WelcomePython'
Changing Strings
l String - “immutable sequence”
l Immutable - you cannot change a string in place
l >>> S = 'spam'
l >>> S[0] = 'x' # Raises an error!
l TypeError: 'str' object does not support item
assignment
l But S = ‘Apple’ works
l How??
Changing Strings
l >>> S = S + 'SPAM!'
l # To change a string, make a new one
l >>> S
l 'spamSPAM!'
l >>> S = S[:4] + 'Burger' + S[−1]
l >>> S
l 'spamBurger!'
Replace
l >>> S = 'splot'
l >>> S = S.replace('pl', 'pamal')
l >>> S
l 'spamalot'
Formatting Strings
l >>> 'That is %d %s bird!' % (1, 'dead')
l That is 1 dead bird!
l >>> 'That is {0} {1} bird!'.format(1, 'dead')
l 'That is 1 dead bird!'
String Library
lPython has a number of string functions which are
in the string library
lThese functions do not modify the original string,
instead they return a new string that has been
altered
String Library
l>>> greet = 'Hello Arun'
l>>> zap = greet.lower()
l>>> print (zap)
lhello arun
l>>> print (‘Hi There'.lower())
lhi there
Searching a String
l find() - function to search for a string within another
l find() - finds the first occurrence of the substring
l If the substring is not found, find() returns -1
l >>> name = 'pradeepkumar‘
l >>> pos = name.find('de')
l >>> print (pos)
l 3
Searching a String
l >>> aa = “fruit”.find('z')
l >>> print (aa)
l -1
l >>> name = 'pradeepkumar‘
l >>> pos = name.find('de‘,5,8)
l >>>pos
l -1
Other Common String Methods in Action
l >>> line.rstrip()
l >>> line.upper()
>>> line.isalpha()
l
False
l
>>> line.endswith('Ni!\n')
l
True
l
>>> line.startswith('The')
l
True
l
Other Common String Methods in Action
True
l
To check if all letters in a String are in
Uppercase
>>> 'a'.isupper()
False
>>> 'A'.isupper()
True
>>> 'AB'.isupper()
True
>>> 'ABc'.isupper()
False
>>>
To check if all letters in a String are in
Lowercase
isupper() function is used to check if all
letters in a string are in upper case
Examples
>>> 'a'.islower()
True
>>> 'aB'.islower()
False
To check if a sentence is in Title case