Chapter 4 - Python String
Chapter 4 - Python String
Chapter 4 - Python String
07/19/23 1
Python String
a = "Hello“
Print(a)
Python String
Example
Loop through the letters in the word "banana":
for x in "banana":
print(x)
String Length
Example:
a = "Hello, World!"
print(len(a))
Check String
Syntax Semantics
dataA + dataB Generates a third string
Example: that is dataB items added
x='ABC' to the end of dataA.
y='DEF'
z=x+y
print(z)
strings Generating a New string (continued)
Syntax Semantics
data * k Generates a new list of
Example: data items repeated k
x='ABC' times. 'ABC' * 3 becomes
'ABCABCABC'
z=x*3
print(z)
strings Generating a New string (continued)
Syntax Semantics
dataA += dataB dataA becomes dataA with
Example: dataB added to the end.
x='ABC' This is the same as dataA
= dataA + dataB
y='DEF'
x+=y
print(x)
strings Generating a New string (continued)
Syntax Semantics
data *= k data becomes data k
Example: times. This is the same as
x='ABC' data = data * k
x*=3
print(x)
Example 1
Negative Indexing
•Use negative indexes to start the slice from the end of the
string:
Example: Get the characters From: "o" in "World!" (position -5)
To, but not included: "d" in "World!" (position -2):
Solution:
b = "Hello, World!"
print(b[-5:-2])
Example 2
Write a Python program to get a string made of the first 2 and the last 2 chars
from a given a string. If the string length is less than 2, return instead of the
empty string.
Sample String : 'w3resource‘
Expected Result : 'w3ce'
def string_both_ends(str):
if len(str) < 2:
return ''
return str[0:2] + str[-2:]
print(string_both_ends('w3resource'))
print(string_both_ends('w3'))
print(string_both_ends('w'))
Example 3
Write a Python function to get a string made of 4 copies of the last two
characters of a specified string (length must be at least 2).
Sample function and result :
insert_end('Python') -> onononon
insert_end('Exercises') -> eseseses
def insert_end(str):
sub_str = str[-2:]
return sub_str * 4
print(insert_end('Python'))
print(insert_end('Exercises'))
Example 4
Write a Python program to get a single string from two given strings,
separated by a space and swap the first two characters of each string.
Sample String : 'abc', 'xyz'
Expected Result : 'xyc abz'
Write a Python program to remove the characters which have odd index
values of a given string.
def odd_values_string(str):
result = ""
for i in range(len(str)):
if i % 2 == 0:
result = result + str[i]
return result
print(odd_values_string('abcdef'))
print(odd_values_string('python'))
Python - Modify Strings
Python has a set of built-in methods that you can use on strings.
method Description
Example 1:
a = "Hello, World!"
print(a.upper())
print(a.lower())
Example 2:
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!“
Example 3:
a = "Hello, World!"
print(a.replace("H", "J"))
Example 4:
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
Python - Modify Strings
Example 4:
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
Example 5:
request = 'eggs and milk and apples'
print(request)
x=request.split( ) # returns ['eggs', 'and', 'milk', 'and', 'apples']
print(x)
x=request.split('and') # returns ['eggs ', ' milk ', ' apples']
print(x)
x=request.split(' and ') # returns ['eggs', 'milk', 'apples']
print(x)
Python - Modify Strings
Example 6:
s="computer information system“
print(s.find("information"))
print(s.find("information“,3))
print(s.find("information",10)) 9
9
-1
Example 8
Write a Python script that takes input from the user and displays that input
back in upper and lower cases.
Sample Output:
What's your favourite language? english
Write a Python program to get a string from a given string where all
occurrences of its first char have been changed to '$', except the first char
itself.
Sample String : 'restart‘
Expected Result : 'resta$t'
def change_char(str1):
char = str1[0]
str1 = str1.replace(char, '$')
str1 = char + str1[1:]
return str1
print(change_char('restart'))
Python - String Format
• You can use index numbers {0} to be sure the arguments are placed in the
correct placeholders:
Example:
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))