You are on page 1of 28

Python Strings

Strings in python are surrounded by either


single quotation marks,
Or
double quotation marks.
Example:
'hello' is the same as "hello".
Assign String to a Variable

Assigning a string to a variable is done with the


variable name followed by an equal sign and the
string:
a = "Hello"
print(a)
Multiline Strings

We can assign a multiline string to a variable by using three quotes:


a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
OR
Or three single quotes:
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)
Strings as Arrays

• Strings in Python are arrays of bytes starting with position 0.


• Square brackets can be used to access elements of the string.
Example
Get the character at position 1 (remember that the first character has the position
0):
a = "Hello, World!"
print(a[1])
Here output will be?????
Note: Python does not have a character data type, a single character is simply a
string with a length of 1.
Looping Through a String

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

To get the length of a string, use the len() function.


a = "Hello, World!"
print(len(a))

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

By leaving out the end index, the range will go to the


end.
Example
Get the characters from position 2, and all the way to the
end.
b = "Hello, World!"
print(b[2:])
OUTPUT:??
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):
b = "Hello, World!"
print(b[-5:-2])
OUTPUT: orl
Modify Strings

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 strip() method removes any whitespace from the beginning


or the end:

a = " Hello, World! "


print(a.strip()) 
Output??????
String Concatenation
To concatenate, or combine, two strings you can use the + operator
Example 1
a = "Hello"
b = "World"
c = a + b
print(c)
Example 2
a = "Hello"
b = "World"
c = a + " " + b
print(c)
String Format

We cannot combine strings and numbers like this:


age = 26
txt = "My name is John, I am " + age
print(txt)
It will give an error message????????
Combine strings and numbers by using the format() method!

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

Where in the text is the word "welcome"?:


txt = "Hello, welcome to my world."
x = txt.find("welcome")
print(x)
OUTPUT: 7
Example 2
txt = "Hello, welcome to my world."
x = txt.find("e")
print(x)
OUTPUT: 1

The find() method finds the first occurrence of the specified value.


The find() method returns -1 if the value is not found.
Syntax
string.find(value, start, end)
Example:
Example
Where in the text is the first occurrence of the letter "e" when you
only search between position 5 and 10?:
txt = "Hello, welcome to my world."

x = txt.find("e", 5, 10)

print(x)
Task 1

Find “q”
in
txt = "Hello, welcome to my world."
Task 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.
solution

def string_both_ends(str):
if len(str) < 2:
return ‘’ “

return str[0:2] + str[-2:]

print(string_both_ends(‘welcome'))
print(string_both_ends(‘we'))
print(string_both_ends('w'))
Task 3

Write a program to accept a string and display the string in


•upper case,
•lower case
•Title case
•Replace upper to lower and vice versa
Task

Program to find the length of a string- welcome

a)Using for loop


b)Using string functions
Solution a)

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

str = input("Enter any String :")


print(str.upper())
print(str.title())
print(str.lower())
print(str.swapcase())

You might also like