String Manipulation in Python
String Manipulation in Python
Overview
"hello world".
String Manipulation
Creation
word = "Hello World"
>>>len(word)
11
Finding
word = "Hello World"
print word.count('l')
# count how many times l is in the string
3
>>> print word.find("H")
# find the word H in the string
0
Keep in mind that python, as many other languages, starts to count from 0!!
>>>word.startswith("H")
True
>>>word.endswith("d")
True
>>>word.endswith("w")
False
Repeat Strings
print "."* 10 # prints ten dots
>>>word.replace("Hello", "Goodbye")
'Goodbye World'
Changing Upper and Lower Case Strings
string = "Hello World"
Python strings have the strip(), lstrip(), rstrip() methods for removing
any character from both ends of a string.
If the characters to be removed are not specified then white-space will be removed
Testing
x = txt.casefold()
print(x)
hello, and welcome to my world!
Overview
List is one of the simplest and most important data structures in Python.
Lists are enclosed in square brackets [ ] and each item is separated by a comma.
Lists are collections of items where each item in the list has an assigned index value.
Lists are very fexible and have many built-in control functions.
Calls to list methods have the list they operate on appear before the method name separated
by a dot, e.g. L.reverse()
Creation
L = ['yellow', 'red', 'blue', 'green', 'black']
>>>print L
returns: ['yellow', 'red', 'blue', 'green', 'black']
##########
Accessing / Indexing
L[0] = returns 'yellow'
##########
Slicing
L[1:4] = returns ['red', 'blue', 'green']
L[2:] = returns ['blue', 'green', 'black']
L[:2] = returns ['yellow', 'red']
L[-1] = returns 'black'
L[1:-1] = returns ['red', 'blue', 'green']
##########
##########
##########
>>> print L
returns: ['black', 'blue', 'green', 'red', 'yellow', 'pink']
##########
>>> print L
returns: ['white', 'black', 'blue', 'green', 'red', 'yellow',
'pink']
##########
L.extend(L2)
##########
L.remove("white")
>>> print L
returns: ['black', 'blue', 'green', 'red', 'yellow', 'pink']
##########
Delete
>>> print L
['blue', 'green', 'red', 'yellow', 'pink']
##########
Pop
##########
##########
Count
##########
if 'red' in L:
print "list contains", 'red'
##########
•lst.append(x)
This method appends an element to the end of the list "lst".
lst=[3,5,7]
lst.append(42)
lst
OUTPUT:
[3, 5, 7, 42]
It's important to understand that append returns "None". In other words, it usually doesn't
make sense to reassign the return value:
lst=[3,5,7]
lst=lst.append(42)
print(lst)
OUTPUT:
None
•lst.pop(i)
'pop' returns the (i)th element of a list "lst". The element will be removed from the list as
well.
cities=["Hamburg","Linz","Salzburg","Vienna"]
cities.pop(0)
OUTPUT:
'Hamburg'
cities
OUTPUT:
['Linz', 'Salzburg', 'Vienna']
cities.pop(1)
OUTPUT:
'Salzburg'
cities
OUTPUT:
['Linz', 'Vienna']
The method 'pop' raises an IndexError exception, if the list is empty or the index is out of
range.
•s.pop()
The method 'pop' can be called without an argument. In this case, the last element will be
returned. So s.pop() is equivalent to s.pop(-1).
cities=["Amsterdam","The Hague","Strasbourg"]
cities.pop()
OUTPUT:
'Strasbourg'
cities
OUTPUT:
['Amsterdam', 'The Hague']
Extend
We saw that it is easy to append an object to a list. What about adding more than one element
to a list? Maybe, you want to add all the elements of another list to your list. If you use
append, the other list will be appended as a sublist, as we can see in the following example:
lst=[42,98,77]
lst2=[8,69]
lst.append(lst2)
lst
OUTPUT:
[42, 98, 77, [8, 69]]
For this purpose, Python provides the method 'extend'. It extends a list by appending all the
elements of an iterable like a list, a tuple or a string to a list:
lst=[42,98,77]
lst2=[8,69]
lst.extend(lst2)
lst
OUTPUT:
[42, 98, 77, 8, 69]
As we have mentioned, the argument of 'extend' doesn't have to be a list. It can be any kind of
iterable. That is, we can use tuples and strings as well:
lst=["a","b","c"]
programming_language="Python"
lst.extend(programming_language)
print(lst)
OUTPUT:
['a', 'b', 'c', 'P', 'y', 't', 'h', 'o', 'n']
lst=["Java","C","PHP"]
t=("C#","Jython","Python","IronPython")
lst.extend(t)
lst
OUTPUT:
['Java', 'C', 'PHP', 'C#', 'Jython', 'Python', 'IronPython']
Tuple Matching in Python is a method of grouping the tuples by matching the second
element in the tuples. It is achieved by using a dictionary by checking the second element in
each tuple in python programming. However, we can make new tuples by taking portions of
existing tuples.
Tuple Syntax
Tup = ('Jan','feb','march')
To write an empty tuple, you need to write as two parentheses containing nothing-
tup1 = ();
For writing tuple for a single value, you need to include a comma, even though there is a
single value. Also at the end you need to write semicolon as shown below.
Tup1 = (50,);
Tuple indices begin at 0, and they can be concatenated, sliced and so on.
Tuple Assignment
Python has tuple assignment feature which enables you to assign more than one variable at a
time. In here, we have assigned tuple 1 with the persons information like name, surname,
birth year, etc. and another tuple 2 with the values in it like number (1,2,3,….,7).
For Example,
(name, surname, birth year, favorite movie and year, profession, birthplace) = Robert
In packing, we place value into a new tuple while in unpacking we extract those values back
into variables.
The comparison starts with a first element of each tuple. If they do not compare to =,< or >
then it proceed to the second element and so on.
It starts with comparing the first element from each of the tuples
#case 1
a=(5,6)
b=(1,4)
if (a>b):print("a is bigger")
else: print("b is bigger")
#case 2
a=(5,6)
b=(5,4)
if (a>b):print("a is bigger")
else: print ("b is bigger")
#case 3
a=(5,6)
b=(6,4)
if (a>b):print("a is bigger")
else: print("b is bigger")
Case1: Comparison starts with a first element of each tuple. In this case 5>1, so the output a
is bigger
Case 2: Comparison starts with a first element of each tuple. In this case 5>5 which is
inconclusive. So it proceeds to the next element. 6>4, so the output a is bigger
Case 3: Comparison starts with a first element of each tuple. In this case 5>6 which is false.
So it goes into the else block and prints “b is bigger.”
Using tuples as keys in dictionaries
Since tuples are hashable, and list is not, we must use tuple as the key if we need to create a
composite key to use in a dictionary.
Example: We would come across a composite key if we need to create a telephone directory
that maps, first-name, last-name, pairs of telephone numbers, etc. Assuming that we have
declared the variables as last and first number, we could write a dictionary assignment
statement as shown below:
directory[last,first] = number
Inside the brackets, the expression is a tuple. We could use tuple assignment in a for loop to
navigate this dictionary.
This loop navigates the keys in the directory, which are tuples. It assigns the elements of each
tuple to last and first and then prints the name and corresponding telephone number.
Dictionary can return the list of tuples by calling items, where each tuple is a key value pair.
a = {'x':100, 'y':200}
b = list(a.items())
print(b)
Deleting Tuples
Tuples are immutable and cannot be deleted. You cannot delete or remove items from a tuple.
But deleting tuple entirely is possible by using the keyword
del
Slicing of Tuple
To fetch specific sets of sub-elements from tuple or list, we use this unique function called
slicing. Slicing is not only applicable to tuple but also for array and list.
#Comparing tuples
#case 1
a=(5,6)
b=(1,4)
if (a>b):print "a is bigger"
else: print "b is bigger"
#case 2
a=(5,6)
b=(5,4)
if (a>b):print "a is bigger"
else: print "b is bigger"
#case 3
a=(5,6)
b=(6,4)
if (a>b):print "a is bigger"
else: print "b is bigger"
#Slicing of Tuple
x = ("a", "b","c", "d", "e")
print x[2:4]
Built-in functions with Tuple
To perform different task, tuple allows you to use many built-in functions like all(), any(),
enumerate(), max(), min(), sorted(), len(), tuple(), etc.
Iterating through tuple is faster than with list, since tuples are immutable.
Tuples that consist of immutable elements can be used as key for dictionary, which is
not possible with list
If you have data that is immutable, implementing it as tuple will guarantee that it
remains write-protected
Summary
Python has tuple assignment feature which enables you to assign more than one variable at a
time.