A String is an object type in Python, that is used to record textual information. String data type is actually a sub-type of a broader classification of object type called sequence. A sequence is an object that contains components placed one after the other, where each object is given a numeric index, which identifies that component and its position within the whole sequence. As Python is a zero indexed based language, the first object of any sequence is always indexed zero. A string is defined using opening and closing delimiters. These delimiters are single or double quotes
Defining strings in Python
Accessing characters of a string in Python
Strings are immutable
Slicing strings
String concatenation
Creating large strings
String Methods: lower()
, upper()
, strip()
, startswith()
, split()
, join()
, find()
, replace()
, format()
String Membership test
char
data type in Python as in C/C++)string1 = 'Hello'
print(string1)
string2 = "World"
print(string2)
string3 = ""
print(string3)
string4 = "A"
print(string4)
Hello World A
# triple quotes string can extend multiple lines
string5 = """Hello, This is
multi-line string"""
print(string5)
string5 = '''Hello, This is
multi-line string'''
print(string5)
Hello, This is multi-line string Hello, This is multi-line string
# Be careful with quotes!
'I'm using single quotes, but will create an error'
The reason for the error above is because the single quote in I'm stopped the string. You can use combinations of double and single quotes to get the complete statement.
"Now I'm ready to use the single quotes inside a string!"
"Now I'm ready to use the single quotes inside a string!"
Escape characters. If there is some where situation where you need a bunch of quotes, you can use escape character ' '. Just make sure you close the end of the string without the escape character .
'Now I\'m ready to use the single quotes inside a string!'
str.index()
methodstr = 'Python Programming is fun'
print('str = ', str)
#access first index
print('str[0] = ', str[0])
# Negative indices start from the opposite end of the string. Hence, -1 index corresponds to the last character
print('str[-1] = ', str[-1])
#access second last index
print('str[-2] = ', str[-2])
#print(str[17]) #access an index out of the range, will get error
#print(str[1.5]) #use numbers other than an integer as index will flag an error
str = Python Programming is fun str[0] = P str[-1] = n str[-2] = u
# To find out the index of a specific character
str = "Python Programming is fun"
str.index('th')
dir()
help(string)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) /var/folders/1t/g3ylw8h50cjdqmk5d6jh1qmm0000gn/T/ipykernel_27309/2810742144.py in <module> ----> 1 help(string) NameError: name 'string' is not defined
#strings are immutable, means string object does not support item assignment
str1 = 'ArifButt'
#str1[5] = 'c'
print(id(str1))
#assigning a new value is valid
str1 = 'python'
print(id(str1))
The object ArifButt
is now orphan, since there is no variable referring to it now and will be collected by Python garbage collector.
string[start:end]
str1 = 'DataScienceToolsAndTechniques'
print(str1[0:4]) # From the start till before the 4th index
print(str1[:4]) # From the start till before the 4th index
print(str1[11:16])
print(str1[19:]) # From the 19th index till the end
print(str1[19:len(str)]) # From the 19th index till the end
#if start is greater than end, it will return empty string
print(str1[5:2])
Data Data Tools Techniques Techniques
string[start:end:step]
str1 = 'DataScienceToolsAndTechniques'
print(str1[::]) # A default step of 1
print(str1[::1]) # A step of 1
print(str1[::2]) # A step of 2
start
index must be greater than the end
index, otherwise an empty string will be returnedstr1 = '0123456789'
print(str1[::-1])
print(str1[5:1:-1])
print(str1[2:10:-1])
print(str1[::-2])
9876543210 5432 97531
+
operatorstr1 = 'Hello'
str2 =' World!'
str3 = str1 + str2
print('str1 + str2 = ', str3)
print("Y" + str3[1:])
*
operatorstr1 = 'Hello'
print('str1 * 5 =', str1 * 5)
buffer = 'A' * 100
print(buffer)
str1 * 3 = HelloHelloHelloHelloHello AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
"Arif"*100
"Hey object, do this to these arguments"
. The syntax to call methods is:object.method(arg1, arg2, ...)
len()
, str.lower()
, str.upper()
and str.capitalize()
methods¶len()
is a built-in function that returns the number of items of a container data type passed as argument. We can check the length of any data types that are collections with built-in len()
function.It is considered a built-in function.
str.lower()
method return a copy of the string converted to lowercase.str.upper()
method return a copy of the string converted to uppercase.str.capitalize()
method return a capitalized version of the string.help(len)
str1= "Hello World"
mylist = [1,2,3,4,5]
len(str1)
len(mylist)
5
str.<tab>
str.lower<shift+tab>
str1="DS"
str.
str1 = 'LearNing is Fun with Arif'
print('Orignial string = ', str1)
rv = len(str1)
print('len(str1) = ', rv)
rv = str1.lower()
print('str1.lower() = ', rv)
print('str1.upper() = ', str1.upper())
rv = str.capitalize()
print('str1.capitalize() = ', rv)
print('Orignial string = ', str1)
Orignial string = LearNing is Fun with Arif len(str1) = 25 str1.lower() = learning is fun with arif str1.upper() = LEARNING IS FUN WITH ARIF str1.capitalize() = Welcome to learning data science with arif Orignial string = LearNing is Fun with Arif
str.strip()
method¶str.strip()
method removes whitespace characters from the beginning and end of a string.str.lstrip()
method removes whitespace characters from the beginning of a string.str.rstrip()
method removes whitespace characters from the end of a string.str1="DS"
help(str1.strip)
buffer =" hello world, this is Arif Butt "
rv = buffer.strip()
print(buffer)
print(rv)
hello world, this is Arif Butt hello world, this is Arif Butt
buffer
buffer.lstrip()
'hello world, this is Arif Butt '
buffer
buffer.rstrip()
' hello world, this is Arif Butt'
str.startswith()
method¶The str.startswith()
method return True if str starts with the specified prefix, False otherwise.
str.startswith(prefix[, start[, end]])
str1="DS"
help(str1.startswith)
str1 = "Learning is fun with Arif Butt"
rv = str1.startswith('Learning')
print(rv)
rv = str1.startswith('Arif')
print(rv)
rv = str1.startswith('Arif', 21)
print(rv)
# case sensitive
rv = str1.startswith('arif', 21)
print(rv)
rv = str1.startswith('arn', 2, 10) # character at ending index is not included
print(rv)
True False True False True
str.split()
and str.join()
method¶str.split()
method splits a string into a list of strings at every occurrence of space character by default. You may pass a parameter sep='i'
to split method to split at that specific character instead.sep.join(list)
method is passed a list/iterable as parameter and is called on a separater character. It joins the strings inside the list to a single string and returnsstr1="DS"
help(str1.split)
str1 = 'Learning is fun with Arif Butt'
rv = str1.split()
print(rv)
print(type(rv))
['Learning', 'is', 'fun', 'with', 'Arif', 'Butt'] <class 'list'>
str1 = 'Learning is fun with Arif Butt'
rv = str1.split(sep='i')
print(rv)
print(type(rv))
['Learn', 'ng ', 's fun w', 'th Ar', 'f Butt'] <class 'list'>
str1="DS"
help(str1.join)
Help on built-in function join: join(iterable, /) method of builtins.str instance Concatenate any number of strings. The string whose method is called is inserted in between each given string. The result is returned as a new string. Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
mystr = "L e a r n i n g"
mystr.split(' ')
['L', 'e', 'a', 'r', 'n', 'i', 'n', 'g']
# The join() method takes all items in an iterable and joins them into one string.
mylist = ['Learning', 'is', 'fun', 'with', 'Arif']
#Note the separator is space character
mystr = ' '.join(mylist)
print(mylist, type(mylist))
print(mystr, type(mystr))
['Learning', 'is', 'fun', 'with', 'Arif'] <class 'list'> Learning is fun with Arif <class 'str'>
# You can call join() method on a separator or your choice
mylist = ['Arif', 'Rauf', 'Maaz', 'Hadeed', 'Mujahid', 'Mohid']
#Note the separator is hash character
mystr = '#'.join(mylist)
print(mylist, type(mylist))
print(mystr, type(mystr))
['Arif', 'Rauf', 'Maaz', 'Hadeed', 'Mujahid', 'Mohid'] <class 'list'> Arif#Rauf#Maaz#Hadeed#Mujahid#Mohid <class 'str'>
str.find()
method¶str.find()
method is used to find a substring from within a string, which returns the first index at which a substring occurs in a string. If no instance of the substring is found, the method returns -1.str.find(substring, start, end)
where
- substring
is what we are searching for,
- start
is the index from where we want to start searching (default value is 0)
- end
is the index where we want to stop our search (default value is len(str) -1)
str1 = 'DataScienceToolsAndTechniques'
print(str1.find('Data'))
print(str1.find('And'))
print(str1.find('S',2)) # second argument starts searching from that index
print(str1.find('s',2)) # case sensitive
print(str1.find('S',0, 4)) # third argument stops searching uptill that index
print(str1.find('S',0, 5))
0 16 4 15 -1 4
str.replace()
method to find a substring¶str.replace()
method returns a string after replacing all occurrences of substring_to_be_replaced
with new_string
.str.replace(substring_to_be_replaced, new_string, count = -1)
replace
returns a new string, and the original string is not modified.str1="DS"
help(str1.replace)
print("hello".replace("e","a"))
str1 = 'Welcome to Learning Data Science with Arif'
newstring = str1.replace('Data Science', 'Life')
print(str1)
print(newstring)
Welcome to Learning Data Science with Arif Welcome to Learning Life with Arif
str.format()
method¶str.format()
method combines values of other data types, e.g., integers, floats, booleans, lists, etc. with strings.str.format()
to construct output messages for display in the Python built-in print()
function.{}
within the format string of print()
function, and the arguments to the str.format()
method are the variable namesstr.format()
method.#Example 1:
age = 51; name="Arif Butt"
print("Mr. {}, you are {} years old." .format(name, age))
#Example 2:
name="Hadeed Butt"
cost = 100
discount = .2
bill = cost - cost * discount
print("Mr. {2}, your total cost is {1}, percentage discount is {3}, and bill is {0}"
. format(bill, cost, name, discount))
is
operator and ==
operator¶# Let us check out the IDs of the following two variables. Like numbers type of variable,
# they are same as both a and b refers to the same memory location containing string 'hello'
a = 'hello'
b = 'hello'
id(a), id(b)
# in case of strings, both a and b refers to the same memory location containing string 'hello'
a = 'hello'
b = 'hello'
# The `is` operator checks the memory address of two strings
print (a is b)
# The `==` operator checks the contents of two strings
print (a == b)
print(a is not b)
print (a != b)
# both x and y refers to two different memory locations containing string 'hello'
x = 'hello'
y = 'bye'
# The `is` operator checks the memory address of two strings
print (x is y)
# The `==` operator checks the contents of two strings
print (x == y)
print(x is not y)
print (x != y)
in
operator¶'a' in 'DataScience'
'th' not in 'python'
Try answering the following questions to test your understanding of the topics covered in this notebook:
'
and '
vs. those created using double quotes, i.e. "
and "
?\n
?.count
, .isalnum
and .isalpha
methods on strings do?.format
method used for? Can you give an example?.format
method instead of string concatenation?