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

Pythonmod4 Shirin

Uploaded by

foxmicky323
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Pythonmod4 Shirin

Uploaded by

foxmicky323
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Python Strings

Strings
Strings in python are surrounded by either single quotation marks, or double
quotation marks.

'hello' is the same as "hello".

You can display a string literal with the print() function:

Example
print('Hello')
output:

Hello
Hello

Quotes Inside Quotes


You can use quotes inside a string, as long as they don't match the quotes
surrounding the string:

Example
print("It's alright")
print("He is called 'Johnny'")
print('He is called "Johnny"')

It's alright
He is called 'Johnny'
He is called "Johnny"

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:

Example
a = "Hello"
print(a)

output:
Hello

Multiline Strings
You can assign a multiline string to a variable by using three quotes:

Example
You can use three double quotes:

a = """Lorem ipsum dolor sit amet,


consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)

Or three single quotes:

Example
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)

Note: in the result, the line breaks are inserted at the same position as in the
code.

Strings are Arrays


Like many other popular programming languages, strings in Python are
arrays of bytes representing unicode characters.

However, Python does not have a character data type, a single character is
simply a string with a length of 1.

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])

output:
e

Looping Through a String


Since strings are arrays, we can loop through the characters in a string, with
a for loop.

Example
Loop through the letters in the word "banana":

for x in "banana":
print(x)

output:

b
a
n
a
n
a

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

Example
The len() function returns the length of a string:

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

13

Check String
To check if a certain phrase or character is present in a string, we can use the
keyword in.

Example
Check if "free" is present in the following text:
txt = "The best things in life are free!"
print("free" in txt)

output:

true

Use it in an if statement:

Example
Print only if "free" is present:

txt = "The best things in life are free!"


if "free" in txt:
print("Yes, 'free' is present.")

output:
Yes, 'free' is present.

Check if NOT
To check if a certain phrase or character is NOT present in a string, we can
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.

Use it in an if statement:

Example
print only if "expensive" is NOT present:

txt = "The best things in life are free!"


if "expensive" not in txt:
print("No, 'expensive' is NOT present.")

output:

No, 'expensive' is NOT present.


Slicing
You can return a range of characters by using the slice syntax.

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:

llo

Note: The first character has index 0.

Slice From the Start


By leaving out the start index, the range will start at the first
character:

Example

Get the characters from the start to position 5 (not included):

b = "Hello, World!"

print(b[:5])

output:

Hello

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:

llo, World!
Python has a set of built-in methods that you can use on strings.

Upper Case
Example
The upper() method returns the string in upper case:

a = "Hello, World!"
print(a.upper())

HELLO, WORLD!

Lower Case
Example
The lower() method returns the string in lower case:

a = "Hello, World!"
print(a.lower())

hello, world!

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()) # returns "Hello, World!"

Hello,World!

Replace String
Example
The replace() method replaces a string with another string:
a = "Hello, World!"
print(a.replace("H", "J"))

Jello, World!

Split String
The split() method returns a list where the text between the specified
separator becomes the list items.

Example
The split() method splits the string into substrings if it finds instances of the
separator:

a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']

['Hello', ' World!']

String Methods
Python has a set of built-in methods that you can use on strings.

Note: All string methods return new values. They do not change the original
string.

Method Description

capitalize() Converts the first character to upper case

casefold() Converts string into lower case

center() Returns a centered string

count() Returns the number of times a specified value occurs in a string


encode() Returns an encoded version of the string

Python Lists mylist =


["apple", "banana", "cherry"]

List
Lists are used to store multiple items in a single variable.

Lists are one of 4 built-in data types in Python used to store collections of
data, the other 3 are Tuple, Set, and Dictionary, all with different qualities
and usage.

Lists are created using square brackets:

Example
Create a List:

thislist = ["apple", "banana", "cherry"]


print(thislist)

['apple', 'banana', 'cherry']

List Items
List items are ordered, changeable, and allow duplicate values.

List items are indexed, the first item has index [0], the second item has
index [1] etc.

Ordered
When we say that lists are ordered, it means that the items have a defined
order, and that order will not change.

If you add new items to a list, the new items will be placed at the end of the
list.

Note: There are some list methods that will change the order, but in general:
the order of the items will not change.
Changeable
The list is changeable, meaning that we can change, add, and remove items
in a list after it has been created.

Allow Duplicates
Since lists are indexed, lists can have items with the same value:

Example
Lists allow duplicate values:

thislist = ["apple", "banana", "cherry", "apple", "cherry"]


print(thislist)
['apple', 'banana', 'cherry', 'apple', 'cherry']

List Length
To determine how many items a list has, use the len() function:

Example
Print the number of items in the list:

thislist = ["apple", "banana", "cherry"]


print(len(thislist))

List Items - Data Types


List items can be of any data type:

Example
String, int and boolean data types:

list1 = ["apple", "banana", "cherry"]


list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
['apple', 'banana', 'cherry']
[1, 5, 7, 9, 3]
[True, False, False]

A list can contain different data types:

Example
A list with strings, integers and boolean values:

list1 = ["abc", 34, True, 40, "male"]


['abc', 34, True, 40, 'male']

type()
From Python's perspective, lists are defined as objects with the data type
'list':

<class 'list'>
Example
What is the data type of a list?

mylist = ["apple", "banana", "cherry"]


print(type(mylist))
<class 'list'>

The list() Constructor


It is also possible to use the list() constructor when creating a new list.

Example
Using the list() constructor to make a List:

thislist = list(("apple", "banana", "cherry")) # note the double


round-brackets
print(thislist)

['apple', 'banana', 'cherry']

Python Collections (Arrays)


There are four collection data types in the Python programming language:

 List is a collection which is ordered and changeable. Allows duplicate


members.
 Tuple is a collection which is ordered and unchangeable. Allows
duplicate members.
 Set is a collection which is unordered, unchangeable*, and unindexed.
No duplicate members.
 Dictionary is a collection which is ordered** and changeable. No
duplicate members.

Access Items
List items are indexed and you can access them by referring to the index
number:

ExampleGet your own Python Server


Print the second item of the list:

thislist = ["apple", "banana", "cherry"]


print(thislist[1])

banana

Note: The first item has index 0.

Negative Indexing
Negative indexing means start from the end

-1 refers to the last item, -2 refers to the second last item etc.

Example
Print the last item of the list:

thislist = ["apple", "banana", "cherry"]


print(thislist[-1])

cherry

Range of Indexes
You can specify a range of indexes by specifying where to start and where to
end the range.

When specifying a range, the return value will be a new list with the specified
items.

Example
Return the third, fourth, and fifth item:
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])

['cherry', 'orange', 'kiwi']


#This will return the items from position 2 to 5.

#Remember that the first item is position 0,

#and note that the item in position 5 is NOT included

Change Item Value


To change the value of a specific item, refer to the index number:

Example
Change the second item:

thislist = ["apple", "banana", "cherry"]


thislist[1] = "blackcurrant"
print(thislist)

['apple', 'blackcurrant', 'cherry']

Change a Range of Item Values


To change the value of items within a specific range, define a list with the
new values, and refer to the range of index numbers where you want to
insert the new values:

Example
Change the values "banana" and "cherry" with the values "blackcurrant" and
"watermelon":

thislist =
["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)

['apple', 'blackcurrant', 'watermelon', 'orange', 'kiwi',


'mango']

Append Items
To add an item to the end of the list, use the append() method:

ExampleGet your own Python Server


Using the append() method to append an item:

thislist = ["apple", "banana", "cherry"]


thislist.append("orange")
print(thislist)

['apple', 'banana', 'cherry', 'orange']

Insert Items
To insert a list item at a specified index, use the insert() method.

The insert() method inserts an item at the specified index:

Example
Insert an item as the second position:

thislist = ["apple", "banana", "cherry"]


thislist.insert(1, "orange")
print(thislist)

['apple', 'orange', 'banana', 'cherry']

Extend List
To append elements from another list to the current list, use
the extend() method.

Example
Add the elements of tropical to thislist:

thislist = ["apple", "banana", "cherry"]


tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)

['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya']

Add Any Iterable


The extend() method does not have to append lists, you can add any
iterable object (tuples, sets, dictionaries etc.).

Example
Add elements of a tuple to a list:

thislist = ["apple", "banana", "cherry"]


thistuple = ("kiwi", "orange")
thislist.extend(thistuple)
print(thislist)

['apple', 'banana', 'cherry', 'kiwi', 'orange']

Remove Specified Item


The remove() method removes the specified item.

Example
Remove "banana":

thislist = ["apple", "banana", "cherry"]


thislist.remove("banana")
print(thislist)

['apple', 'cherry']

If there are more than one item with the specified value,
the remove() method removes the first occurrence:

Example
Remove the first occurrence of "banana":

thislist = ["apple", "banana", "cherry", "banana", "kiwi"]


thislist.remove("banana")
print(thislist)

['apple', 'cherry', 'banana', 'kiwi']

Remove Specified Index


The pop() method removes the specified index.

Example
Remove the second item:

thislist = ["apple", "banana", "cherry"]


thislist.pop(1)
print(thislist)

['apple', 'cherry']

If you do not specify the index, the pop() method removes the last item.

Example
Remove the last item:

thislist = ["apple", "banana", "cherry"]


thislist.pop()
print(thislist)

['apple', 'banana']

The del keyword also removes the specified index:

Example
Remove the first item:

thislist = ["apple", "banana", "cherry"]


del thislist[0]
print(thislist)

['banana', 'cherry']

You might also like