Download as pdf or txt
Download as pdf or txt
You are on page 1of 82

Strings

Accessing Values in Strings


 Strings are immutable.
 Ex:
var1 = 'Hello World!'
var2 = "Python Programming"
print("var1[0]:",var1[0])
print("var2[1:5]:",var2[1:5])
print("var2[1:]:",var2[1:])
print("var2[:5]:",var2[:5])

 Output:
var1[0]: H
var2[1:5]: ytho
var2[1:]: ython Programming
var2[:5]: Pytho
 Ex:
var1 = 'Hello World!'
print("Updated String: ", var1[:6] + 'Python')
var2 = 'HelloWorld!'
print("Updated String: ", var2[:6] + 'Python')

 Output:
Updated String: Hello Python
Updated String: HelloWPython
 Ex:

str = 'programiz‘
print('str = ', str)

#first character
print('str[0] = ', str[0])

#last character
print('str[-1] = ', str[-1])

print('str[1:5] = ', str[1:5])

print('str[5:-2] = ', str[5:-2])

# index must be in range


print(‘str[15]=‘,str[15])
 Output:
str = programiz
str[0] = p
str[-1] = z
str[1:5] = rogr
str[5:-2] = am
IndexError: string index out of range
Ex:
pi = 3.14
text = 'The value of pi is ' + pi #NO, does not work
text = 'The value of pi is ' + str(pi) #yes

Output:
TypeError: can not concatenate 'str‘ and 'float‘ objects
 Ex:

# all of the following are equivalent


my_string = 'Hello‘
print(my_string)
my_string = "Hello“
print(my_string)
my_string = '''Hello''‘
print(my_string)

# triple quotes string can extend multiple lines


my_string = """Hello, welcome to
the world of Python"“”
print(my_string)
 Output:
Hello
Hello
Hello
Hello, welcome to
the world of Python
How to change or delete a string?
 Strings are immutable. This means that elements of a string
cannot be changed once it has been assigned. We can
simply reassign different strings to the same name.

 >>> my_string = 'programiz'


>>> my_string[5] = 'a'
TypeError: 'str' object does not support item assignment

>>> my_string = 'Python'


>>> my_string
'Python'
 We cannot delete or remove characters from a string. But
deleting the string entirely is possible using the keyword del.

 >>> del my_string[1]


TypeError: 'str' object doesn't support item deletion

>>>del my_string
>>> my_string
NameError: name 'my_string' is not defined
Iterating Through String
 Ex: to count no. of ‘l’ in a string

count = 0
for letter in 'Hello World':
if(letter == 'l'):
count += 1
print('%d letters found' %count)
Escape Sequence
 If we want to print a text like - He said, "What's there?"- we can
neither use single quote or double quotes. This will result
into SyntaxError as the text itself contains both single and double
quotes.

 >>> print("He said, "What's there?"")


SyntaxError: invalid syntax
>>> print('He said, "What's there?"')
SyntaxError: invalid syntax
 One way to get around this problem is to use triple quotes.
Alternatively, we can use escape sequences.
 Ex:
# using triple quotes
print('''He said, "What's there?"''')

# escaping single quotes


print('He said, "What\'s there?"')

# escaping double quotes


print("He said, \"What's there?\"")

 Output:
He said, "What's there?"
He said, "What's there?"
He said, "What's there?"
 Ex:
print("C:\\Python32\\Lib")
print("This is printed\nin two lines")
print("This is \x48\x45\x58 representation")

 Output:
C:\Python32\Lib
This is printed
in two lines
This is HEX representation
String special operators
 Assume string variable a holds 'Hello' and variable b holds
'Python', then −
 a='hello '
b='world'
print(a+b)
print(a*3)
print(a[1])
print(a[1:4])
print('a' in a)
print(not 'a' in a)
print('\n')
print(r'\n')

 Output:
hello world
hello hello hello
e
ell
False
True

\n
 Ex:
print("This is \x61 \ngood example")
print(r"This is \x61 \ngood example")

 Output:
This is a
good example
This is \x61 \ngood example
 Writing two string literals together also concatenates them
like + operator.
 If we want to concatenate strings in different lines, we can use
parentheses.

 Ex:
print('Hello ''World!')
s = ('Hello '
'World!')
print(s)

 Output:
Hello World!
Hello World!
The format() Method for Formatting
Strings
 The format() method that is available with the string object is very
versatile and powerful in formatting strings. Format strings contains
curly braces {} as placeholders.
 We can use positional arguments or keyword arguments to specify
the order.
 Ex:

# default(implicit) order
default_order = "{}, {} and {}".format('John','Bill','Sean')
print('\n--- Default Order ---')
print(default_order)

# order using positional argument


positional_order = "{1}, {0} and {2}".format('John','Bill','Sean')
print('\n--- Positional Order ---')
print(positional_order)

# order using keyword argument


keyword_order = "{s}, {b} and {j}".format(j='John',b='Bill',s='Sean')
print('\n--- Keyword Order ---')
print(keyword_order)
 Output:

--- Default Order ---


John, Bill and Sean
--- Positional Order ---
Bill, John and Sean

--- Keyword Order ---


Sean, Bill and John
 Example of positional and keyword arguments in format() method:

#positional arguments
print("Hello {0}, your balance is {1:f}".format("Adam",230.2346))
print("Hello {0}, your balance is {1:3f}".format("Adam",230.2346))
print("Hello {0}, your balance is {1:10.3f}".format("Adam",230.2346))
print("Hello {0}, your balance is {1}".format("Adam",230.2346))

#keyword arguments
print("Hello {name}, your balance is
{blc:9.3f}".format(name="Adam",blc=230.2346))

 Output:
Hello Adam, your balance is 230.234600
Hello Adam, your balance is 230.234600
Hello Adam, your balance is 230.235
Hello Adam, your balance is 230.2346
Hello Adam, your balance is 230.235
 Ex:
# default arguments
print("Hello {}, your balance is {}.".format("Adam", 230.2346))
# positional arguments
print("Hello {0}, your balance is {1}.".format("Adam", 230.2346))
# keyword arguments
print("Hello {name}, your balance is {blc}.".format(name="Adam",
blc=230.2346))
# mixed arguments
print("Hello {0}, your balance is {blc}.".format("Adam", blc=230.2346))

 Output:
Hello Adam, your balance is 230.2346.
Hello Adam, your balance is 230.2346.
Hello Adam, your balance is 230.2346.
Hello Adam, your balance is 230.2346.
Numbers formatting with format()
 Ex:
# integer arguments
print("The number is:{:d}".format(123))
# float arguments
print("The float number is:{:f}".format(123.4567898))
# octal, binary and hexadecimal format
print("bin: {0:b}, oct: {0:o}, hex: {0:x}".format(12))

 Output:
The number is:123
The float number is:123.456790
bin: 1100, oct: 14, hex: c
 Ex:

# integer numbers with minimum width


print("{:5d}".format(12))

# width doesn't work for numbers longer than padding


print("{:2d}".format(1234))

# padding for float numbers


print("{:8.3f}".format(12.2346))

# integer numbers with minimum width filled with zeros


print("{:05d}".format(12))

# padding for float numbers filled with zeros


print("{:08.3f}".format(12.2346))
Number formatting with alignment
 Ex:
print("{:5d}".format(12))
print("{:^10.3f}".format(12.2346))
print("{:<05d}".format(12))
print("{:=8.3f}".format(-12.2346))
 Ex:
# string padding with left alignment
print("{:<5}".format("cat"))
# string padding with right alignment
print("{:>5}".format("cat"))
# string padding with center alignment
print("{:^5}".format("cat"))
# string padding with center alignment
# and '*' padding character
print("{:*^5}".format("cat"))
Truncating strings with format()
 Ex:
# truncating strings to 3 letters
print("{:.3}".format("caterpillar"))
# truncating strings to 3 letters
# and padding
print("{:<5.3}".format("caterpillar"))
# truncating strings to 3 letters,
# padding and center alignment
print("{:^5.3}".format("caterpillar"))
String Formatting Operator
 One of Python's coolest features is the string format operator %. This operator
is unique to strings and makes up for the pack of having functions from C's
printf() family. Following is a simple example −
 Ex:
print("My name is %s and weight is %d kg!" % ('Zara', 21))
 Output:
My name is Zara and weight is 21 kg!
 Ex:
print("My name is %s and weight is %d kg!" % ('Zara', 21))
print("The character is %c" %'Z')
print("My value is %i " %1.0)
print("My value is %e " %10)
print("My value is %f" %10)

 Output:
My name is Zara and weight is 21 kg!
The character is Z
My value is 1
My value is 1.000000e+01
My value is 10.000000
Methods of String Objects
 capitalize()
Capitalizes first letter of string

Ex:
str = “hello world”
print("str.capitalize() : ", str.capitalize())

Output:
str.capitalize() : Hello world
 center(width, fillchar)
Returns a space-padded string with the original string centered to a
total of width columns. Padding is done using the specified fillchar.
Default filler is a space.

Ex:
str = "hello!"
print("str.center() : ", str.center(10, 'a'))
print("str.center() : ", str.center(10))
str="hello"
print("str.center() : ", str.center(10, 'a'))
Output:
str.center() : aahello!aa
str.center() : hello!
str.center() : aahelloaaa
count(str, beg= 0,end=len(string))
Counts how many times str occurs in string or in a substring of string if starting index
beg and ending index end are given.

Ex:
str = "this is string example....wow!!!"
sub = "i"
print("str.count() : ", str.count(sub))
print("str.count() : ", str.count("i"))
print("str.count() : ", str.count(sub,4))
print("str.count() : ", str.count(sub,4,40))
print("str.count() : ", str.count(sub,4,11))
print("str.count() : ", str.count(sub,4,12))
Output:
str.count() : 3
str.count() : 3
str.count() : 2
str.count() : 2
str.count() : 1
str.count() : 2
startswith(str, beg=0,end=len(string))
Determines if string or a substring of string (if starting index beg and
ending index end are given) starts with substring str; returns true if so and
false otherwise.

Ex:
str = "this is string example....wow!!!“
print(str.startswith( 'this' ))
print(str.startswith( 'is', 2, 4 ))
print(str.startswith( 'this', 2, 4 ))

Output:
True
True
False
endswith(suffix, beg=0, end=len(string))
Determines if string or a substring of string (if starting index beg and ending index
end are given) ends with suffix; returns true if so and false otherwise.

Ex:
str = "hello world!!!"
suffix = "world!!!"
print(str.endswith(suffix))
print(str.endswith(suffix,3))
print(str.endswith(suffix,10))
suffix="llo"
print(str.endswith(suffix,2,5))
print(str.endswith(suffix,2,4))
print(str.endswith(suffix,2)) #default end slice is ending of string
Output:
True
True
False
True
False
False
expandtabs(tabsize=8)
Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if
tabsize not provided.

Ex:
str = “h\te\tl\tl\to”
print("Original string: " , str)
print("Default exapanded tab: " , str.expandtabs())
print("Double exapanded tab: " , str.expandtabs(16))
Output:
Original string: h e l l o
Default exapanded tab: h e l l o
Double exapanded tab: h e l l
o
find(str, beg=0 end=len(string))
Determine if str occurs in string or in a substring of string if starting index
beg and ending index end are given returns index if found and -1
otherwise.

Ex:
str1 = "this is string example....wow!!!"
str2 = "exam"
print(str1.find(str2))
print(str1.find(str2, 10))
print(str1.find(str2, 40))
print(str1.find(str2,10,20))
Output:
15
15
-1
15
rfind(str, beg=0,end=len(string))
The method rfind() returns the last index where the substring str is found,
or -1 if no such index exists, optionally restricting the search to
string[beg:end].

Ex:
str1 = "this is really a string example....wow!!!“
str2 = "is“
print(str1.rfind(str2))
print(str1.rfind(str2, 0, 10))
print(str1.rfind(str2, 10, 0))
print(str1.find(str2))
print(str1.find(str2, 0, 10))
print(str1.find(str2, 10, 0))
Output:
5
5
-1
2
2
-1
index(str, beg=0, end=len(string))
Same as find(), but raises an exception if str not found.

Ex:
str1 = "this is string example....wow!!!"
str2 = "exam"
print(str1.index(str2))
print(str1.index(str2, 10))
print(str1.index(str2, 40))
print(str1.index(str2,10,20))
Output:
15
15
Traceback (most recent call last):
File "C:/Users/WEBSERVER/PycharmProjects/untitled/test.py", line 5, in
<module>
print str1.index(str2, 40)
ValueError: substring not found
rindex( str, beg=0, end=len(string))
The method rindex() returns the last index where the substring str is
found, or raises an exception if no such index exists, optionally restricting
the search to string[beg:end].

Ex:
str1 = "this is string example....wow!!!“
str2 = "is“
print(str1.rindex(str2))
print(str1.index(str2))

Output:
5
2
isalnum()
Returns true if string has at least 1 character and all characters are
alphanumeric and false otherwise.

Ex:
str = "this2009“ # space not allowed
print(str.isalnum())
str = "this is string example....wow!!!“
print(str.isalnum())

Output:
True
False
isalpha()
Returns true if string has at least 1 character and all characters are alphabetic
and false otherwise.

Ex:
str = "this2009"
print(str.isalpha())
str = "this is string example....wow!!!"
print(str.isalpha())
str = "this 2009"
print(str.isalpha())
str = "1234"
print(str.isalpha())
str = ""
print(str.isalpha())
str = "hello"
print(str.isalpha())
Output:
False
False
False
False
False
True
isdigit()
Returns true if string contains only digits and false otherwise.

Ex:
str = "123456" # Only digit in this string
print(str.isdigit())
str = "this is string example....wow!!!"
print(str.isdigit())

Output:
True
False
islower()
This method returns true if all cased characters in the string are
lowercase and there is at least one cased character, false otherwise.

Ex:
str = "THIS is string example....wow!!!"
print(str.islower())
str = "this is string example....wow!!!"
print(str.islower())
str = "t"
print(str.islower())
str = ""
print(str.islower())
Output:
False
True
True
False
isspace()
Returns true if string contains only whitespace characters and false
otherwise.

Ex:
str = " "
print(str.isspace())
str = "This is string example....wow!!!"
print(str.isspace())

Output:
True
False
istitle()
The method istitle() checks whether all the case-based characters in the
string following non-case based letters are uppercase and all other
case-based characters are lowercase.

Ex:
str = "This Is String Example...Wow!!!"
print(str.istitle())
str = "This is string example....wow!!!"
print(str.istitle())

Output:
True
False
isupper()
The method isupper() checks whether all the case-based characters
(letters) of the string are uppercase.

Ex:
str = "THIS IS STRING EXAMPLE....WOW!!!“
print str.isupper()
str = "THIS is string example....wow!!!“
print str.isupper()

Output:
True
False
title()
The method title() returns a copy of the string in which first characters of
all the words are capitalized.

Ex:
str = "this is string example....wow!!!“
print(str.title())

Output:
This Is String Example....Wow!!!
upper()
Converts lowercase letters in string to uppercase.

Ex:
str = "this is string example....wow!!!“
print("str.capitalize() : ", str.upper())

Output:
THIS IS STRING EXAMPLE....WOW!!!
lower()
Converts all uppercase letters in string to lowercase.

Ex:
str = "THIS IS STRING EXAMPLE....WOW!!!“
print(str.lower())

Output:
this is string example....wow!!!
swapcase()
Inverts case for all letters in string.

Ex:
str = "this is string example....wow!!!“
print(str.swapcase())
str = "THIS IS STRING EXAMPLE....WOW!!!“
print(str.swapcase())

Output:
THIS IS STRING EXAMPLE....WOW!!!
this is string example....wow!!!
join(seq)
The method join() returns a string in which the string elements of
sequence have been joined by str separator.

Ex:
s = "-“
seq = ("a", "b", "c") # This is sequence of strings.
print(s.join(seq))

Output:
a-b-c
split()
The method split() returns a list of all the words in the string, using str as
the separator (splits on all whitespace if left unspecified), optionally
limiting the number of splits to num.

Ex:
str = "Line1-abcdef Line2-abc Line4-abcd"
print(str.split( ))
print(str.split())
print(str.split(' ', 0 ))
print(str.split(' ', 1 ))
print(str.split(' ', 2 ))
print(str.split(' ', 3 ))
Output:
['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
['Line1-abcdef Line2-abc Line4-abcd']
['Line1-abcdef', 'Line2-abc Line4-abcd']
['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
len(string)
Returns the length of the string

Ex:
str = "this is string example....wow!!!"
print("Length of the string: ", len(str))

Output:
32
ljust(width[, fillchar])
The method ljust() returns the string left justified in a string of
length width. Padding is done using the specified fillchar (default is a
space). The original string is returned if width is less than len(s).

Ex:
str = "this is string example....wow!!!“
print(str.ljust(50, '0'))

Output:
this is string example....wow!!!000000000000000000
rjust(width,[, fillchar])
The method rjust() returns the string right justified in a string of
lengthwidth. Padding is done using the specified fillchar (default is a
space). The original string is returned if width is less than len(s).

Ex:
str = "this is string example....wow!!!“
print(str.rjust(50, '0'))

Output:
000000000000000000this is string example....wow!!!
lstrip()
The method lstrip() returns a copy of the string in which all chars have
been stripped from the beginning of the string (default whitespace
characters).

Ex:
str = “this is string example....wow!!! “
print(str.lstrip())
str = "88888888this is string example....wow!!!8888888“
print(str.lstrip('8'))

Output:
this is string example....wow!!!
this is string example....wow!!!8888888
rstrip()
The method rstrip() returns a copy of the string in which all chars have
been stripped from the end of the string (default whitespace
characters).

Ex:
str = "this is string example....wow!!! “
print(str.rstrip())
str = "88888888this is string example....wow!!!8888888“
print(str.rstrip('8'))

Output:
this is string example....wow!!!
88888888this is string example....wow!!!
strip([chars])
Performs both lstrip() and rstrip() on string

Ex:
str = "0000000this is string example....wow!!!0000000“
print(str.strip( '0' ))

Output:
this is string example....wow!!!
max(str)
The method max() returns the max alphabetical character from the
string str.

Ex:
str = "this is really a string example....wow!!!“
print("Max character: " , max(str))
str = "this is a string example....wow!!!“
print("Max character: " , max(str))

Output:
Max character: y
Max character: x
min(str)
The method min() returns the min alphabetical character from the
string str.

Ex:
str = "this-is-real-string-example....wow!!!“
print("Min character: " , min(str))
str = "this-is-a-string-example....wow!!!"
print("Min character: " , min(str))

Output:
Min character: !
Min character: !
replace(old, new [, max])
The method replace() returns a copy of the string in which the
occurrences ofold have been replaced with new, optionally restricting
the number of replacements to max.

Ex:
str = "this is string example....wow!!! this is really string“
print(str.replace("is", "was"))
print(str.replace("is", "was", 3))

Output:
thwas was string example....wow!!! thwas was really string
thwas was string example....wow!!! thwas is really string
zfill (width)
The method zfill() pads string on the left with zeros to fill width.

Ex:
str = "this is string example....wow!!!“
print str.zfill(40)
print str.zfill(50)

Output:
00000000this is string example....wow!!!
000000000000000000this is string example....wow!!!
str() and repr()
 str() and repr() both are used to get a string representation of object.
s = 'Hello, Geeks.'
print (str(s))
print (str(2.0/11.0))
print (repr(s))
print (repr(2.0/11.0))
 Output:
Hello, Geeks.
0.18181818181818182
'Hello, Geeks.'
0.18181818181818182
 str() is used for creating output for end user while repr() is mainly used
for debugging and development. repr’s goal is to be unambiguous
and str’s is to be readable.

 repr() compute the “official” string representation of an object (a


representation that has all information about the object) and str() is
used to compute the “informal” string representation of an object (a
representation that is useful for printing the object).
import datetime
today = datetime.datetime.now()

# Prints readable format for date-time object


print (str(today))

# prints the official format of date-time object


print (repr(today))

Output:
2021-04-27 20:08:17.532933
datetime.datetime(2021, 4, 27, 20, 8, 17, 532933)

You might also like