0% found this document useful (0 votes)
107 views18 pages

Python - String

This document provides an introduction to strings and lists in Python 3. It discusses tuples, strings, and lists as data types that share similar syntax and functionality. It explains how to access individual items, slice subsets, represent memory, use membership and mathematical operators, and various string functions to manipulate string data.

Uploaded by

Nabihah Husna
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
107 views18 pages

Python - String

This document provides an introduction to strings and lists in Python 3. It discusses tuples, strings, and lists as data types that share similar syntax and functionality. It explains how to access individual items, slice subsets, represent memory, use membership and mathematical operators, and various string functions to manipulate string data.

Uploaded by

Nabihah Husna
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 18

PYTHON PROGRAMMING

(PYTHON 3.X using Jupyter Notebook)


String and Lists

DSC551 – PROGRAMMING FOR DATA SCIENCE

Pn Marhainis Jamaludin
Faculty of Computer and Mathematical Sciences
Introduction
These data types share most of the same syntax and
functionality:
• Tuple
• Simple immutable ordered sequence of items.
• Items can be of mixed types.
• Strings
• Immutable
• Conceptually similar to tuple
• Lists
• Mutable ordered sequence of items of mixed types.
In Python, everything is an object. All objects created in Python can either be
mutable or immutable
• Tuple is defined by using parentheses () and commas
• Example:
>>>tp = (23, ‘abc’, 4.56, (2,3), ‘def’)

• List is defined by using square bracket [] and commas


• Example:
>>>li = [23, ‘abc’, 4.56, [2,3], ‘def’)

• Strings are defined using quotes (“, ‘, OR “””)


• Example:
>>>st = “Hello World”
>>>st = ‘Hello World’
>>>st = “””This is multi-line strings””” #block quotes
How to access the individual item?
• The item in tuple, list or string can be accessed
individually by using the index, which is always starts
at 0.
• Index can be positive (+) or negative (-)
• Positive(+) index reads data from left starting from 0
• Negative(-) index reads data from right, starting from
-1
• Example:
Slicing
• Returns the subset of the members.
• Starts 1st index and stop before the 2nd index
• Example:
>>>t = [23, ‘abc’, 4.56, [2,3], ‘def’]
>>>t[1:4]
[‘abc’, 4.56, [2,3])
>>>t[1: -1]
[‘abc’, 4.56, [2,3]]
>>>t[:2] #missing 1st index will starts from 0
[23, ‘abc’]
>>>t[2:] #missing 2nd index, end of container
[4.56, [2,3], ‘def’]
>>>t[:] #missing 1st and 2nd index, list the whole container
[23, ‘abc’, 4.56, [2,3], ‘def’]
Memory Representation
Example:
>>>a = [1,2,3]
a

>>>b = a #2 names refer to 1 object, changes made to one will affect both

>>>b = a[:] #2 different copies will be created and 2 references


a

b
IN operator
Membership operator. Returns True if the first operand
contains within the second operand, otherwise False.
Example:
>>> a = [1,2,3,4,5]
>>> 3 in a
True
>>> 3 not in a
False
>>> s = ‘abcde’
>>> ‘c’ in s
True
>>> ‘ac’ in s
False
+ operator
• Concatenation operator to produce a new list
• Example:
>>>[1,2,3] + [7,8]
[1,2,3,7,8]

>>> s = ‘CS’
>>> y = ‘241’
>>>s + y
‘CS241’
>>>print (‘Good Luck’ + ‘!!!!’)
Good Luck!!!
* operator
• Create new list that replicates the original list.
• Example:
>>> [1,2,3] * 3
[1,2,3,1,2,3,1,2,3]
>>> ‘x’ * 3
‘xxx’
STRING
Various String Operators
OPERATOR DESCIPTION EXAMPLE

[] Slice x = “abcdef’
it gives the characters from the given index print (x[1])
-> b
[:] Range slice x = “abcdef”
it gives the characters from the given range print (x[1:3])
-> bc
in Membership x = “abcdef”
Returns true if a letter exist in a given string ‘c’ in x
-> True
not in Membership x = “abcdef”
Returns true if a letter does not exist in the given string ‘n’ not in x
-> True
% Used for string format x = “abcdef”
It inserts the canonical string representation of the object print(“it is %s” %x)
-> it is abcdef
+ Concatenates 2 strings x = ‘abc’
y = ‘stu’
print (x + y)
-> abcstu
* Repeat x = ‘abc’
print (x *2)
-> abcabc
String Functions
• Some of the common functions which can be used to manipulate string data.
Function Description Example

capitalize() Converts the 1st character to upper case x = "dsc551 is programming for data science“
x.capitalize()
-> Dsc551 is programming for data science
title() Capitalize the first letter of each word in a string x = "dsc551 is programming for data science“
x.title()
->Dsc551 Is Programming For Data Science

You can also use the string package capwords(), import string
but need to import the string package string.capwords(x)
->Dsc551 Is Programming For Data Science

upper() Converts string to upper case x = "dsc551 is programming for data science“
x.upper()
->DSC551 IS PROGRAMMING FOR DATA SCIENCE

lower() Converts string to lower case x = "dsc551 is programming for data science“
x.lower()
->dsc551 is programming for data science
count() Returns the number of times a specified value x = "dsc551 is programming for data science“
occurs in a string x.count(‘m’)
->2
Function Description Example
index() Searches a string for a specified value and returns x = "dsc551 is programming for data science“
the position of where it was found. x.index(‘m’)
->16

isdigit() Returns True if the string are digits or numeric y="12345“


isnumeric() y.isdigit()
->True

y.isnumeric()
->True
islower() Returns True fi the string are lower case x = "dsc551 is programming for data science“
x.islower()
->True
isalpha() Returns True if the string are alphabet x = "dsc551 is programming for data science“
x.isalpha()
->False
len() Returns the length of the string x = "dsc551 is programming for data science“
print (len(x))
This function is not a string object. ->38
strip() Returns a trimmed version of the string. Strip the x = "dsc551 is programming for data science“
1st letter of a string, if true x.strip(‘d’)
->sc551 is programming for data science

x.strip(‘c’)
->dsc551 is programming for data science
Function Description Example

replace() Returns a string where specified value x = "dsc551 is programming for data science“
is replaced with a specified value x.replace(‘m’, ‘@’)
->dsc551 is progra@@ing for data science

x.replace(‘programming’, ‘aturcara’)
->dsc551 is aturcara for data science
find() Searches a string for a specified value x = "dsc551 is programming for data science“
and returns the position of where it x.find(‘g’)
was found ->13

x.find(‘m’)
->16

x.find(‘for’)
->22
split() Splits the string at the specified x = "dsc551 is programming for data science“
separator/delimiter and returns a list x.split(‘ ‘)
->['dsc551', 'is', 'programming', 'for', 'data', 'science’]

join() Joins the string at the specified x = "dsc551 is programming for data science“
separator and returns a list. Much ' and '.join(x)
flexible to do concatenation of strings ->d and s and c and 5 and 5 and 1 and and i and s and and p and
where you can add any characters in r and o and g and r and a and m and m and i and n and g and
the string and f and o and r and and d and a and t and a and and s and c
and i and e and n and c and e
Function Description Example
reversed() Returns the reversed of the string x = "dsc551 is programming for data science“
''.join(reversed(x))
->ecneics atad rof gnimmargorp si 155csd

z = "abcdef“
list(reversed(z))
->['f', 'e', 'd', 'c', 'b', 'a']

Example:
i =x.find('for’)
w = x[:i] + "language”
print(w)

-> dsc551 is programming language

Example:
b = x.split(' ‘)
print(b)
-> ['dsc551', 'is', 'programming', 'for', 'data', 'science’]

' and '.join(b)


->dsc551 and is and programming and for and data and science
References
• https://realpython.com/python-strings/
• https://www.guru99.com/learning-python-strings-
replace-join-split-reverse.html
• https://medium.com/@meghamohan/mutable-
and-immutable-side-of-python-c2145cf72747

You might also like