Python - Strings
Python - Strings
Python - Strings
Since strings are like arrays, we can loop through the characters in a string, with a for loo
Example
Loop through the letters in the word “LPU":
for x in “LPU":
print(x)
OUTPUT:
L
P
U
String Length
OUTPUT: 13
How to check a string
Example
Check if "free" is present in the following text:
txt = "The best things in life are free!"
print("free" in txt)
OUTPUT: True
Another way
Print only if "free" is present:
txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.")
Check if NOT
In order to check if a certain phrase is NOT present in a string, use the keyword not in
Example
Check if "expensive" is NOT present in the following text:
txt = "The best things in life are free!"
print("expensive" not in txt)
OUTPUT: True
OR by using if statement……
Example
txt = "The best things in life are free!"
if "expensive" not in txt:
print("No, 'expensive' is NOT present.")
String Slicing
If you want to slice a string, specify the start index and the end
index, separated by a colon, to return a part of the string.
Example
Get the characters from position 2 to position 5 (not
included):
b = "Hello, World!"
print(b[2:5])
Output:??????
Note: The first character has index 0
Slice From the Start
Example
Get the characters from the start to position 5 (not
included):
b = "Hello, World!"
print(b[:5])
OUTPUT:
??????
Slice To the End
Upper Case
The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())
Lower Case
The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower())
Remove Whitespace
Whitespace is the space before and/or after the actual text,
and very often you want to remove this space.
Example
The format() method takes the passed arguments, formats them, and places them in the
string where the placeholders {} are:
Example 1:
Use the format() method to insert numbers into strings:
age = 20
txt = "My name is John, and I am {}"
print(txt.format(age))
OUTPUT: My name is John, and I am 20
Example 2:
The format() method takes unlimited number of arguments, and are placed into the respective
placeholders:
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
find() in strings
x = txt.find("e", 5, 10)
print(x)
Task 1
Find “q”
in
txt = "Hello, welcome to my world."
Task 2
def string_both_ends(str):
if len(str) < 2:
return ‘’ “
print(string_both_ends(‘welcome'))
print(string_both_ends(‘we'))
print(string_both_ends('w'))
Task 3
def findLen(str):
counter = 0
for i in str:
counter += 1
return counter
str = “welcome"
print(findLen(str))
Solution b)
str = “welcome"
print(len(str))
solution