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

Week 07 String

Uploaded by

Prachee Mahato
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Week 07 String

Uploaded by

Prachee Mahato
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 39

Week 07 – Strings

Python Programming
CT108-3-1-PYP
Complied by: Subash Khatiwada
TOPIC LEARNING OUTCOMES

At the end of this topic, you should be able to:


– Understand what is strings
– Understand how to search, find and loop through string

Python Programming Strings SLIDE 2


CT108-3-1-PYP
Contents & Structure

Defining string type of data

Searching through string

Finding element in a string

Looping through string/ list


Python Programming Strings SLIDE 3
CT108-3-1-PYP ‹#›
Strings
A Python strings is a datatype be it a letter, number, punctuation or any other keyboard character

To initialize enclose the text with a single or double quote


stringTitle = “Minecraft” stringSubtitle = ‘Awesome Game’

To include a quote in the string use the backward slash


stringSubtitle = ‘It\’s an awesome game’

This tells the interpreter, this is an apostrophe, not an opening quote to another string, so ignore it.

In python, strings are treated as a special type of list

Python uses Unicode format to represent characters.

Python Programming Strings SLIDE 4


CT108-3-1-PYP ‹#›
String Data Type -recap
>>> str1 = "Hello” A string is a sequence of
>>> str2 = 'there' characters
>>> bob = str1 + str2
>>> print(bob) A string literal uses quotes
Hellothere 'Hello' or “Hello”

>>> str3 = '123' For strings, + means


>>> str3 = str3 + 1 “concatenate”
Traceback (most recent call last): File
"<stdin>", line 1, in When a string contains
<module>TypeError: cannot numbers, it is still a string
concatenate 'str' and 'int' objects
>>> x = int(str3) + 1 We can convert numbers
>>> print(x) in a string into a number
124
using int()

Python Programming Strings SLIDE 5


CT108-3-1-PYP ‹#›
Reading and Printing a string

name = input("Enter your name:")


print('Hi ' + name + ' Lets learn about strings in Python!')

Python Programming Strings SLIDE 6


CT108-3-1-PYP ‹#›
String Concatenation

Joining of two or more strings into one is called concatenation.

The + operator does this in Python.


>>> a = "Hello"
>>> b = a + "There"
>>> print(b)
HelloThere
>>> c = a + ' ' + 'There'
>>> print (c)
Hello There
The * operator can be used to repeat the string for a given number
of times
>>> word = 'hello'
>>> print(word * 3)
hellohellohello

Python Programming Strings SLIDE 7


CT108-3-1-PYP ‹#›
Reading and Converting

>>> name = input('Enter: ')


Enter: Alice We prefer to read data in
>>> print(name) using strings and then
Alice parse and convert the
data as we need
>>> apple = input('Enter: ')
Enter:100 This gives us more control
over error situations
>>> x = apple – 10
and/or bad user input
Traceback (most recent call last): File
"<stdin>", line 1, in
<module>TypeError: unsupported
operand type(s) for -: 'str' and 'int’ Raw input numbers must
be converted from strings
>>> x = int(apple) – 10
>>> print(x)
90

Python Programming Strings SLIDE 8


CT108-3-1-PYP ‹#›
Strings are sequences

A string is a sequence of characters.


• Each character in the string has an index.
-3 -2 -1
abc = a b c
Index 0 1 2
:
• Expression retrieving a character at specified index:
<str-expr> [ <index-expr> ]
"abc"[0]  a "abc"[2]  c

"abc"[1]  b len("abc")  3

Python Programming Strings SLIDE 9


CT108-3-1-PYP
Accessing Individual Characters

We can access individual name = 'Aziah Binti Abdollah’


print('First character is '+name[0])
characters of string using print('Last character is '+name[-1])
indexing. print('Fifth character is '+name[5])

If we try to access index out of the range or use decimal


number, we will get errors. So be careful when constructing
index values and slices

The index value must be an integer and starts at zero

Python Programming Strings SLIDE 10 ‹#›


CT108-3-1-PYP
Special characters

• The backslash is used to introduce a Escape Meaning


special character. sequence
print("He said, "Wow!"")
\\ Backslash
File "<stdin>", line 1
"He said, "Wow!"" \’ Single quote
^
SyntaxError: invalid syntax \” Double
print("He said, 'Wow!'")
He said, 'Wow!’
quote
print("He said, \"Wow!\"") \n Newline
He said, "Wow!"
\t Tab

Python Programming Strings SLIDE 11


CT108-3-1-PYP
The print separator and end

By default, print() separates multiple outputs with spaces

You can change this to any string that you want, for example, a colon and a space (': ')
>>> print(1, 2, 3, sep=': ')
1: 2: 3

By default, print() ends its output with a newline ('\n')
>>> for i in range(3):
print(i) Passing the whitespace to the end parameter
0 (end=' ') indicates that the end character must be
1 identified by whitespace and not a newline.
2

You can change this, for example, to a hyphen
>>>for i in range(3):
print(i, end='-')
0-1-2-

Python Programming Strings SLIDE 12


CT108-3-1-PYP
Using in as an Operator

The in keyword can also be used to check to see if one string is


"in" another string

The in expression is a logical fruit = 'banana'


print('n' in fruit)
expression and returns True or print('m' in fruit)

False and can be used in an if print('nan' in fruit)


if 'a' in fruit :
statement print ('Found it!')

Python Programming Strings SLIDE 13


CT108-3-1-PYP ‹#›
More string functionality

>>> print(len("GATTACA")) #Length


7
>>> print("GAT" + "TACA") #Concatenate
GATTACA
>>> print("A" * 10) #Repeat
AAAAAAAAAA
>>> print("GAT" in "GATTACA") #in operators
True
>>> print("AGT" in "GATTACA")
False

Python Programming Strings SLIDE 14


CT108-3-1-PYP
Strings Have Length

• There is a built-in function len that gives us the length of a string

>>> fruit = 'banana'


>>> print(len(fruit)) b a n a n a
6 0 1 2 3 4 5

Python Programming Strings SLIDE 15


CT108-3-1-PYP
Iterating over strings

name = "Alice" name = "Alice"


for c in name: for i in range(len(name)):
print(str(i) +" "+ name[i])
print(c)

A 0 A
l 1 l
i 2 i
c 3 c
e 4 e

Python Programming Strings SLIDE 16


CT108-3-1-PYP
Slicing Strings – What is it?
Slicing means taking part of a string as in cutting it up

It is often useful to take part of a string or analyse it or use it is another part


of the code.

Example:

One of the checks will mean that you


You have been asked to write a
need to slice the string taking all the
program to check if a string contains
characters from the left-hand part of
a valid address.
the string up to character

Python Programming Strings SLIDE 18 ‹#›


CT108-3-1-PYP
Slicing Strings –How to do it?

Strings have indices just like lists:

• Forward index starts at 0 from the LHS


• Reverse index starts at -1 from the RHS

Forward 0 1 2 3 4 5 6 7 8
index
M i n e c r a f t
-9 -8 -7 -6 -5 -4 -3 -2 -1 Reverse
index

To specify a slice, you need to

• give the START position from the left-hand side


• give the END position from the left-hand side
• Separate the two values with a colon

Example:

• newString = myString [1:3]

Python Programming Strings SLIDE 19 ‹#›


CT108-3-1-PYP
Slicing Strings –Some Rules

• If did not specify a START it defaults to the beginning:


newString = myString[:3] This means start at
position 0 end at position 3

• If did not specify an END it defaults to the end:

newString = myString[3:] This means start at


position until the end

0 1 2 3 4 5 6 7 8
When SLICING, think of
the index as pointing to M i n e c r a f t
the character to the left
of the arrow -9 -8 -7 -6 -5 -4 -3 -2 -1

Python Programming Strings SLIDE 20


CT108-3-1-PYP ‹#›
Slicing Strings – Quickstart

0 1 2 3 4 5 6 7 8
M i n e c r a f t
-9 -8 -7 -6 -5 -4 -3 -2 -1
• First Character M
firstChar = myString[0]

• Last Character
t
lastChar = myString[-1]

• All characters but the first


slice =myString[1:] inecraft
• All characters but the last
slice = myString[:-1] Minecraf

Python Programming Strings SLIDE 21


CT108-3-1-PYP ‹#›
Accessing substrings - Slicing

>>> myString = “GATTACA”


>>> myString[1:3]
‘AT’
>>> myString[:3]
‘GAT’
>>> myString[4:]
‘ACA’
>>> myString[3:5]
‘TA’
>>> myString[:]
‘GATTACA’

Python Programming Strings SLIDE 22


CT108-3-1-PYP
String Method

Python has several string functions which are in the


string library.
These functions are already built into every string - we
invoke them by appending the function to the string
variable

These functions do not modify the original string,


instead they return a new string that has been altered

Python Programming Strings SLIDE 23


CT108-3-1-PYP
Strings are objects

• Objects have methods.

<expr> .method()

• Some string methods:


"abc abc".capitalize()  Abc abc

"abc abc".count("b")  2

"abc abc".islower()  True

• Strings are immutable.

Python Programming Strings SLIDE 24


CT108-3-1-PYP
Strings are immutable

• Strings cannot be modified; instead, create a new one.

>>> s = "GATTACA"
>>> s[3] = "C"
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: object doesn't support item assignment
>>> s = s[:3] + "C" + s[4:]
>>> s
'GATCACA'
>>> s = s.replace("G","U")
>>> s
'UATCACA'

Python Programming Strings SLIDE 25


CT108-3-1-PYP
Strings are immutable

String methods do not modify the string; they return a new string.
>>> sequence = "ACGT"
>>> print(sequence.replace("A", "G"))
GCGT
>>> print(sequence)
ACGT
Or
>>> sequence = "ACGT"
>>> new_sequence = sequence.replace("A", "G")
>>> print(new_sequence)
GCGT

Python Programming Strings SLIDE 26


CT108-3-1-PYP
Strings are immutable

When a string method returns a string, it is a different object; the original
string is not changed
>>> aStr = 'my cat is catatonic’
>>> newStr = aStr.replace('cat', 'dog’)
>>> print(newStr)
???
>>> print(aStr)
???
•However, you can associate the old string name with the new object
>>> aStr = 'my cat is catatonic’
>>> aStr = aStr.replace('cat', 'dog’)
>>> print(aStr)
???

Python Programming Strings SLIDE 27


CT108-3-1-PYP
Some more string methods

"AbC aBc".lower()  abc abc

"abc abc".replace("c ", "xx")  abxx abxx

"abc abc".startswith("ab")  True

"AbC aBc".swapcase()  aBc AbC

"Abc abc".upper()  ABC ABC

Python Programming Strings SLIDE 28


CT108-3-1-PYP
The string format method

The string format() method allows you detailed control over what is printed and
its arrangement (including alignment; width; your choice of date, time and
number formats; and many other things).

Here is an example of how s.format() can be used to control what is printed:
>>> print('{} is {}'.format('Big Bird', 'yellow'))
Big Bird is yellow
>>> fname = 'Hari'
>>> mname = 'Prasad'
>>> lname = 'Pandey'
>>> print(f"His full name is {fname} {mname} {lname}")
>>> print("His full name is {} {}
{}“.format(fname,mname,lname))

Python Programming Strings SLIDE 29


CT108-3-1-PYP
UPPER CASE VS LOWER CASE

>>> greet = 'Hello Bob'


>>> nnn = greet.upper()
>>> print(nnn) You can make a copy of a
HELLO BOB string in lower case or upper
>>> www = greet.lower()
case
>>> print(www)
hello bob
Often when we are searching
for a string using find() - we
first convert the string to
lower case so we can search
a string regardless of case

Python Programming Strings SLIDE 30


CT108-3-1-PYP ‹#›
Searching a String
• We use the find() function b a n a n a
to search for a substring 0 1 2 3 4 5
within another string.
• find() finds the first >>> fruit = 'banana'
occurrence of the >>> pos = fruit.find('na')
substring. >>> print pos
2
• If the substring is not
>>> aa = fruit.find('z')
found, find() returns -1
>>> print aa
• Remember that string -1
position starts at zero
Python Programming Strings SLIDE 31
CT108-3-1-PYP
Stripping Whitespace

Sometimes we want to >>> greet = ' Hello Bob '


take a string and remove >>> greet.lstrip()
whitespace at the 'Hello Bob '
beginning and/or end >>> greet.rstrip()
' Hello Bob'
lstrip() and rstrip() to the >>> greet.strip()
left and right only 'Hello Bob'

strip() Removes both


begin and ending
whitespace

Python Programming Strings SLIDE 32


CT108-3-1-PYP ‹#›
Built-in String Methods:
1 capitalize()

Capitalizes first letter of string


2 center(width, fillchar)

Returns a space-padded string with the original string centered to a total of width
columns
3 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
3 decode(encoding='UTF-8',errors='strict')

Decodes the string using the codec registered for encoding. encoding defaults to the
default string encoding.
4 encode(encoding='UTF-8',errors='strict')

Returns encoded string version of string; on error, default is to raise a ValueError


unless errors is given with 'ignore' or 'replace'.
5 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
6 expandtabs(tabsize=8)

Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not
provided

Python Programming Strings SLIDE 33


CT108-3-1-PYP
7 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
8 index(str, beg=0, end=len(string))

Same as find(), but raises an exception if str not found

9 isa1num()

Returns true if string has at least 1 character and all characters are alphanumeric
and false otherwise
10 isalpha()

Returns true if string has at least 1 character and all characters are alphabetic and
false otherwise
11 isdigit()

Returns true if string contains only digits and false otherwise

12 islower()

Returns true if string has at least 1 cased character and all cased characters are in
lowercase and false otherwise
13 isnumeric()

Returns true if a unicode string contains only numeric characters and false otherwise

14 isspace()

Returns true if string contains only whitespace characters and false otherwise

Python Programming Strings SLIDE 34


CT108-3-1-PYP
15 istitle()

Returns true if string is properly "titlecased" and false otherwise


16 isupper()

Returns true if string has at least one cased character and all cased characters are in
uppercase and false otherwise
17 join(seq)

Merges (concatenates) the string representations of elements in sequence seq into a


string, with separator string
18 len(string)

Returns the length of the string


19 ljust(width[, fillchar])

Returns a space-padded string with the original string left-justified to a total of width
columns
20 lower()

Converts all uppercase letters in string to lowercase


21 lstrip()

Removes all leading whitespace in string


22 maketrans()

Returns a translation table to be used in translate function.


23 max(str)

Returns the max alphabetical character from the string str


Python Programming Strings SLIDE 35
CT108-3-1-PYP
24 min(str)

Returns the min alphabetical character from the string str

25 replace(old, new [, max])

Replaces all occurrences of old in string with new, or at most max occurrences if max
given
26 rfind(str, beg=0,end=len(string))

Same as find(), but search backwards in string

27 rindex( str, beg=0, end=len(string))

Same as index(), but search backwards in string

28 rjust(width,[, fillchar])

Returns a space-padded string with the original string right-justified to a total of width
columns.
29 rstrip()

Removes all trailing whitespace of string

30 split(str="", num=string.count(str))

Splits string according to delimiter str (space if not provided) and returns list of
substrings; split into at most num substrings if given
31 splitlines( num=string.count('\n'))

Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs
removed
Python Programming Strings SLIDE 36
CT108-3-1-PYP
32 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
33 strip([chars])

Performs both lstrip() and rstrip() on string

34 swapcase()

Inverts case for all letters in string

35 title()

Returns "titlecased" version of string, that is, all words begin with uppercase, and the
rest are lowercase
36 translate(table, deletechars="")

Translates string according to translation table str(256 chars), removing those in the
del string
37 upper()

Converts lowercase letters in string to uppercase

38 zfill (width)

Returns original string leftpadded with zeros to a total of width characters; intended
for numbers, zfill() retains any sign given (less one zero)
39 isdecimal()

Returns true if a unicode string contains only decimal characters and false otherwise

Python Programming Strings SLIDE 37


CT108-3-1-PYP
Summary / Recap of Main Points

• String type
• Read/Convert
• Indexing strings []
• Slicing strings [2:4]
• Looping through strings with for and while
• Concatenating strings with +
• String operations

Python Programming Strings SLIDE 38


CT108-3-1-PYP
What To Expect Next Week

In Class Preparation for Class


• List • Understand the use of List.
• What is the different between
strings and list.

Python Programming Strings SLIDE 39


CT108-3-1-PYP
Python Programming Strings SLIDE 40
CT108-3-1-PYP

You might also like