0% found this document useful (0 votes)
2 views

String Manipulation in Python

The document provides an overview of string and list manipulation in Python, detailing the characteristics and methods associated with each data type. It covers string creation, accessing, slicing, and various built-in functions for manipulation, as well as list creation, indexing, slicing, and methods for modifying lists. Additionally, it introduces tuples, explaining their syntax, packing, unpacking, and comparison.

Uploaded by

sourav.me.klc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

String Manipulation in Python

The document provides an overview of string and list manipulation in Python, detailing the characteristics and methods associated with each data type. It covers string creation, accessing, slicing, and various built-in functions for manipulation, as well as list creation, indexing, slicing, and methods for modifying lists. Additionally, it introduces tuples, explaining their syntax, packing, unpacking, and comparison.

Uploaded by

sourav.me.klc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

String Manipulation in Python

Overview

A string is a list of characters in order.

A character is anything you can type on the keyboard in one keystroke,


like a letter, a number, or a backslash.

Strings can have spaces:

"hello world".

An empty string is a string that has 0 characters.

Python strings are immutable

Python recognize as strings everything that is delimited by quotation marks


(” ” or ‘ ‘).

String Manipulation

To manipulate strings, we can use some of Pythons built-in methods.

Creation
word = "Hello World"

>>> print word


Hello World
Accessing

Use [ ] to access characters in a string

word = "Hello World"


letter=word[0]

>>> print letter


H
Length
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

>>> print word.index("World")


# find the letters World in the string
6
Count
s = "Count, the number of spaces"

>>> print s.count(' ')


8
Slicing

Use [ # : # ] to get set of letter

Keep in mind that python, as many other languages, starts to count from 0!!

word = "Hello World"

print word[0] #get one char of the word


print word[0:1] #get one char of the word (same as above)
print word[0:3] #get the first three char
print word[:3] #get the first three char
print word[-3:] #get the last three char
print word[3:] #get all but the three first char
print word[:-3] #get all but the three last character

word = "Hello World"

word[start:end] # items start through end-1


word[start:] # items start through the rest of the list
word[:end] # items from the beginning through end-1
word[:] # a copy of the whole list
Split Strings
word = "Hello World"

>>>word.split(' ') # Split on whitespace


['Hello', 'World']
Startswith / Endswith
word = "hello world"

>>>word.startswith("H")
True

>>>word.endswith("d")
True

>>>word.endswith("w")
False
Repeat Strings
print "."* 10 # prints ten dots

>>> print "." * 10


..........
Replacing
word = "Hello World"

>>>word.replace("Hello", "Goodbye")
'Goodbye World'
Changing Upper and Lower Case Strings
string = "Hello World"

>>> print string.upper()


HELLO WORLD

>>> print string.lower()


hello world

>>> print string.title()


Hello World

>>> print string.capitalize()


Hello world

>>> print string.swapcase()


hELLOwORLD
Reversing
string = "Hello World"

>>> print ' '.join(reversed(string))


d l r o W o l l e H
Strip

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

word = "Hello World"

Strip off newline characters from end of the string

>>> print word.strip('


')
Hello World

strip() #removes from both ends


lstrip() #removes leading characters (Left-strip)
rstrip() #removes trailing characters (Right-strip)

>>> word = " xyz "

>>> print word


xyz

>>> print word.strip()


xyz

>>> print word.lstrip()


xyz

>>> print word.rstrip()


xyz
Concatenation

To concatenate strings in Python use the “+” operator.

"Hello " + "World" # = "Hello World"


"Hello " + "World" + "!"# = "Hello World!"
Join
>>> print ":".join(word) # #add a : between every char
H:e:l:l:o: :W:o:r:l:d

>>> print " ".join(word) # add a whitespace between every char


H e l l o W o r l d

Testing

A string in Python can be tested for truth value.

The return type will be in Boolean value (True or False)

word = "Hello World"

word.isalnum() #check if all char are alphanumeric


word.isalpha() #check if all char in the string are alphabetic
word.isdigit() #test if string contains digits
word.istitle() #test if string contains title words
word.isupper() #test if string contains upper case
word.islower() #test if string contains lower case
word.isspace() #test if string contains spaces
word.endswith('d') #test if string endswith a d
word.startswith('H') #test if string startswith H
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
Searches the string for a specified value and returns the position of where it was
find()
found
format() Formats specified values in a string
format_map() Formats specified values in a string
Searches the string for a specified value and returns the position of where it was
index()
found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isascii() Returns True if all characters in the string are ascii characters
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Converts the elements of an iterable into a string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
Searches the string for a specified value and returns the last position of where it
rfind()
was found
Searches the string for a specified value and returns the last position of where it
rindex()
was found
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the beginning
txt = "hello, and welcome to my world."
x = txt.capitalize()
print (x)
Hello, and welcome to my world.
--------------------------------------------------------------
-------------

txt = "Hello, And Welcome To My World!"

x = txt.casefold()

print(x)
hello, and welcome to my world!

List Manipulation in Python

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.

A list is mutable, meaning you can change its contents.

Lists are very fexible and have many built-in control functions.

Methods of List objects

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']

##########

Length - number of items in list


len(L) = returns 5

##########

Sorting - sorting the list


sorted(L) = returns ['black', 'blue', 'green', 'red',
'yellow']

##########

Append - append to end of list


L.append("pink")

>>> print L
returns: ['black', 'blue', 'green', 'red', 'yellow', 'pink']

##########

Insert - insert into list


L.insert(0, "white")

>>> print L
returns: ['white', 'black', 'blue', 'green', 'red', 'yellow',
'pink']

##########

Extend - grow list

L.extend(L2)

##########

Remove - remove first item in list with value "white"

L.remove("white")

>>> print L
returns: ['black', 'blue', 'green', 'red', 'yellow', 'pink']

##########
Delete

Remove an item from a list given its index instead of its


value
del.L[0]

>>> print L
['blue', 'green', 'red', 'yellow', 'pink']

##########

Pop

Remove last item in the list


L.pop() = returns 'pink'

# remove indexed value from list


L.pop(1) = returns 'green'

##########

Reverse - reversing the list


L.reverse()

##########

Count

Search list and return number of instances found


L.count('red')

##########

Keyword "in" - can be used to test if an item is in a list

if 'red' in L:
print "list contains", 'red'

##########

For-in statement - makes it easy to loop over the items in a


list
for item in L:
print item

L = ['red', 'blue', 'green']


for col in L:
print col

•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']

Now with a tuple:

lst=["Java","C","PHP"]
t=("C#","Jython","Python","IronPython")
lst.extend(t)
lst
OUTPUT:
['Java', 'C', 'PHP', 'C#', 'Jython', 'Python', 'IronPython']

Python TUPLE – Pack, Unpack, Compare, Slicing, Delete, Key


What is Tuple Matching in Python?

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

Here is the code,


tup1 = ('Robert', 'Carlos','1965','Terminator 1995',
'Actor','Florida');
tup2 = (1,2,3,4,5,6,7);
print(tup1[0])
print(tup2[1:4])

 Tuple 1 includes list of information of Robert


 Tuple 2 includes list of numbers in it
 We call the value for [0] in tuple and for tuple 2 we call the value between 1 and 4
 Run the code- It gives name Robert for first tuple while for second tuple it gives
number (2,3 and 4)
Packing and Unpacking

In packing, we place value into a new tuple while in unpacking we extract those values back
into variables.

x = ("Guru99", 20, "Education") # tuple packing


(company, emp, profile) = x # tuple unpacking
print(company)
print(emp)
print(profile)
Comparing tuples

A comparison operator in Python can work with tuples.

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

Let’s study this with an example-

#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.

for last, first in directory:


print first, last, directory[last, first]

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.

Tuples and dictionary

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.

x = ("a", "b","c", "d", "e")


print(x[2:4])

The output of this code will be (‘c’, ‘e’).

Here is the Python 2 Code for all above example

tup1 = ('Robert', 'Carlos','1965','Terminator 1995',


'Actor','Florida');
tup2 = (1,2,3,4,5,6,7);
print tup1[0]
print tup2[1:4]

#Packing and Unpacking


x = ("Guru99", 20, "Education") # tuple packing
(company, emp, profile) = x # tuple unpacking
print company
print emp
print profile

#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"

#Tuples and dictionary


a = {'x':100, 'y':200}
b = a.items()
print b

#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.

Advantages of tuple over list

 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.

 Packing and Unpacking of Tuples


 In packing, we place value into a new tuple while in unpacking we extract those
values back into variables.
 A comparison operator in Python can work with tuples.
 Using tuples as keys in dictionaries
 Tuples are hashable, and list are not
 We must use tuple as the key if we need to create a composite key to use in a
dictionary
 Dictionary can return the list of tuples by calling items, where each tuple is a
key value pair
 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”
 To fetch specific sets of sub-elements from tuple or list, we use this unique function
called slicing

You might also like