0% found this document useful (0 votes)
8 views29 pages

15 String

The document is an online course on string operations supported by UNESCO UNITWIN and Handong Global University. It covers various aspects of strings in programming, including string composition, operators, methods, and exercises for practical understanding. The course emphasizes the importance of string manipulation in programming and provides examples and exercises for learners to practice their skills.

Uploaded by

Thae Thae Aung
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views29 pages

15 String

The document is an online course on string operations supported by UNESCO UNITWIN and Handong Global University. It covers various aspects of strings in programming, including string composition, operators, methods, and exercises for practical understanding. The course emphasizes the importance of string manipulation in programming and provides examples and exercises for learners to practice their skills.

Uploaded by

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

UNESCO UNITWIN

Online Course
Supported by

Handong Global University


Ministry of Education, Korea

* All copyrights belong to UNESCO UNITWIN and it is prohibited to use these educational materials including the video and other
relevant materials for commercial and for-profit use.
String
15
Global Leadership School
Handong Global University
Learning Objectives
• Understand String
• Understand String Operation
• Understand Methods for String and exercise
String
• String is a list of characters
• String can hold Korean, English, and numbers

>>> name = ‘apple’


>>> print(name[0])
‘a’
>>> school = ‘HGU’
>>> address = ‘558, Handong-ro, Heunghae-
eup, Buk-gu, Pohang-si, Gyeongsangbuk-do‘
The composition of the string
Variable Name Stored Data

str “lemon” “12345” “HGU”


str[0] “l” “1” “H”

str[1] “e” “2” “G”


str[2] “m” “3” “U”
str[3] “o” “4” IndexError
str[4] “n” “5” IndexError
Operator used in the string(1)
• arithmetic operator: + , *

>>> s1 = ‘Cutty’
>>> s2 = ‘Cat’
>>> s3 = s1 + s2
>>> s3
‘CuttyCat’

>>> s1*3
‘CuttyCuttyCutty’
>>> ‘@’ * 10
‘@@@@@@@@@@’
Operator used in the string(2)
• Relational operator: >, >=, <, <=, ==, !=

>>> s1 = ‘cat’
>>> s2 = ‘Cat’

>>> s1== s2
False
>>> s1==‘cat’
True

>>> s1 > ‘bird’


True
String, len()
• len()
• returns the length of a string, the number of chars in it

>>> fruit = 'banana'


>>> len(fruit)
6
>>> length = len(fruit)
>>> last = fruit[length]
IndexError: string index out of range

>>> last = fruit[length-1]


>>> last
a
Loop with a string
fruit="apple“

index = 0
while index < len(fruit) : 0
letter = fruit[index] 1
print(letter) 2
3
index = index + 1
4

fruit="apple“
for loop is shorter
a p pl e
for ch in fruit :
print(ch)
Cut String, String Slice
• A part of string is called ‘slice’
• Slicing is similar to indexing but needs to specify
the range of index for the slice.
>>> s = 'Monty Python'
>>> s[0:5] # index 0,1,2,3,4
Monty
>>> s[6:12] # index 6,7,8,9,10,11
Python
>>> s[1:3] # index 1,2
on
>>> fruit = 'banana'
>>> fruit[:3] # index 0,1,2
'ban'
>>> fruit[3:] # index from 3 to last
'ana'
Exercise 1
• Receive string from user
• If the inputted string is ‘apple’…
• Make a loop with len() function
• Code the input string to be output as follows
• ‘a’
• ‘ap’
• ‘app’
• ‘appl’
• ‘apple’
Exercise 1, Code and Result
input_str = input(”Enter a string: ")

l = len(input_str)

index = 0
while index < l :
print("s[0:", index+1, "]=", input_str[0 : index+1])
index = index + 1
String methods, .upper()
• Method can take argument and return values
• This is similar to function
• However, the syntax is different
• Variable name, dot(.), then write method name
• Method .upper()
• Change all characters to capitals

>>> word = 'banana'


>>> new_word = word.upper()
>>> new_word
BANANA
String methods, .find()
• Find letter in a string
• Returns the index where the character is located

>>> word = 'banana'


>>> index = word.find('a')
>>> index
1
>>> word.find('na')
2
>>> word.find('na', 3) # second number – index to start the search
4
>>> name = 'bob'
>>> name.find('b', 1, 2) # third number – index to end the search
-1
String Methods
.capitalize() Converts the first character to .isupper() Returns True if all characters in the string
upper case are upper case

.count() Returns the number of times a .join() Joins the elements of an iterable to
specified value occurs in a string the end of the string
.find() Searches the string for a specified .lower() Converts a string into lower case
value and returns the position of
where it was found
.isalpha() Returns True if all characters in .replace() .replace(old, new [,count])
the string are in the alphabet Returns a string where a specified value is
replaced with a specified value
.isdigit() Returns True if all characters in .split() Splits the string at the specified
the string are digits separator, and returns a list

.islower() Returns True if all characters in .swapcase() Swaps cases, lower case becomes upper
the string are lower case case and vice versa

.isspace() Returns True if all characters in .upper() Converts a string into upper case
the string are whitespaces
in operator
>>> 'a' in 'banana'
True
>>> 'seed' in 'banana'
False
>>> ‘ana’ in ‘banana’
True

# Use function
def in_both(word1, word2) :
for letter in word1 :
if letter in word2 :
print(letter)

in_both('apples', 'oranges')
Exercise 2
• Receive string from user
• Enter characters or strings to replace with uppercase
letters.
• Change the letter to capital letters and print out
• Example
• Input string “apple”
• Letters to change “le”
• Output “appLE”
Exercise 2, Code and Result

Input_Str = input(”Input String: ")


Input_find = input(”String to change: ")

Index = Input_Str.find(Input_find)

if Index == -1 :
print(" No character to change!")
else:
find_Length = len(Input_find)
beforeStr = Input_Str[0 : Index]
changeStr = Input_Str[Index : Index+find_Length].upper()
afterStr = Input_Str[Index+find_Length : ]
result = beforeStr + changeStr + afterStr
print(result)
Exercise 3
• Receive string from user
• Convert capital letters to small letters and small
letters to capital letters, then print
• After conversion, print number of capital letters, small
letters, and non-letter characters
Exercise 3, Code and Result
str = input(”Enter a string: ")
uppercount = 0
lowercount = 0
etccount = 0

swapstr = str.swapcase()
print(”After swapping cases = ", swapstr)

for ch in swapstr :
if ch.isupper() :
uppercount+=1
elif ch.islower() :
lowercount +=1
else :
etccount +=1
print(”Number of capital letters ", uppercount)
print(”Number of lowercase letters ", lowercount)
print(”Number of non-alphabet characters ", etccount)
Exercise 4
• Receive string from user
• Change the first letter of the string to uppercase
letters, and the rest to lowercase letters
• Print first character of the string and the rest
separately
Exercise 4, Result and Code
str = input(”Enter a string: ")

strChange = str.lower()
strChange = str.capitalize()

print(”First letter: ", strChange[0])

length = len(strChange)
print(”The rest: ", strChange[1: length])
Lecture Summary
• Understand String
• List of characters
• String can hold Korean, English, and capitals
• Understand String Operation
• Arithmetic operator(+, *), Relational operator(>, >=, <,
<=, ==, !=)
• Understand methods for string and exercise
• .upper(), .find()
Practice problem 1
• What's the result of the execution?
name = ‘Blueberry’
print(name[0:1])
• ‘B’
• ‘Bl’
• ‘y’
• ‘ry’
Practice problem 1, Answer
• What's the result of the execution?
name = ‘Blueberry’
print(name[0:1])
• ‘B’
• ‘Bl’
• ‘y’
• ‘ry’
Practice problem 2
• What's the result of the execution?
w = ‘Blueberry’
print(w.find(‘e’, 3))
• 3
• 4
• 5
• 6
Practice problem 2, Answer
• What's the result of the execution?
w = ‘Blueberry’
print(w.find(‘e’, 3))
• 3
• 4
• 5
• 6
Thank you
15 String
Contact Info
[email protected]
https://ecampus.handong.edu/

* All copyrights belong to UNESCO UNITWIN and it is prohibited to use these educational
materials including the video and other relevant materials for commercial and for-profit use.
CREDITS: This presentation template was created by Slidesgo, including icons by Flaticon, and infographics & images by Freepik.

You might also like