KEMBAR78
Pythen String | PDF | Computer Programming | Software Engineering
0% found this document useful (0 votes)
15 views10 pages

Pythen String

The document provides a comprehensive overview of Python programming concepts, including data structures like lists, tuples, sets, and dictionaries, as well as string manipulation techniques. It covers syntax for loops, comments, and various string methods such as slicing, concatenation, and formatting. Additionally, it explains how to modify lists and their built-in methods for managing data effectively.

Uploaded by

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

Pythen String

The document provides a comprehensive overview of Python programming concepts, including data structures like lists, tuples, sets, and dictionaries, as well as string manipulation techniques. It covers syntax for loops, comments, and various string methods such as slicing, concatenation, and formatting. Additionally, it explains how to modify lists and their built-in methods for managing data effectively.

Uploaded by

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

kPs;nray;: VNjDk; xU $w;iw my;yJ xU njhFjp $w;wpidg; gy Kiw kPz;Lk; kPz;Lk; tupirahfr;

nray;gLj;jy;.
igj;jd; nkhop gpd;tUk; jlkply; $w;Wf;fis toq;Ffpd;wJ.

 while

 for

 while loops

njhlupay; (syntax) :

for jlk;

for jlkhdJ xU njhliu (gl;bay; (list)> tup (tuple), mfuhjp (dictionary)> njhFjp (Set) my;yJ ruk; (String))
kPs;nrayhf;Ftjw;Fg; gad;gLj;jg;gLfpd;wJ.

Syntex

for variable name in structure:

suit

Python Comments
Comments start with a #, and Python will ignore them:
Multiline Comments
Python does not really have a syntax for multiline comments.
To add a multiline comment you could insert a # for each line:
#This is a comment
#written in
#more than just one line
print("Hello, World!")
OR
Using triple quotes
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")

khw;wf;$ba juTf; fl;likg;Gfs; (Mutable Data structures)

1. Numbe
2. String
3. gl;bay; (Lists)
4. njhFg;Gfs; (Tuples)
5. mfuhjpfs; (Dictionaries)

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:
print("Hello")
print('Hello')
Quotes Inside Quotes
You can use quotes inside a string, as long as they don't match the quotes surrounding the string:
print("It's alright")
print("He is called 'Johnny'")
print('He is called "Johnny"')
Assign String to a Variable
a = "Hello"
print(a)
Multiline Strings
You 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)
Strings are Arrays
a = "Hello, World!"
print(a[1])
Looping Through a String
Since strings are arrays, we can loop through the characters in a string, with a for loop.
for x in "banana":
print(x)
String Length
To get the length of a string, use the len() function.
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
txt = "The best things in life are free!"
print("free" in txt)
output: True
Use it in an if statement:
txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.")

Slicing Strings
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.
b = "Hello, World!"
print(b[2:5])
output:
llo

Slice From the Start


By leaving out the start index, the range will start at the first character:
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:
b = "Hello, World!"
print(b[2:])
output: llo, World!
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())

output: HELLO, WORLD!


The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower())

Remove White space


Whitespace is the space before and/or after the actual text, and very often you want to
remove this space.
The strip()method removes any white space from the beginning or the end:
a =" Hello, World! "
print(a.strip())# returns "Hello, World!"

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

Split String
The split()method returns a list where the text between the specified separator becomes
the list items.
The split() method splits the string into substrings if it finds instances of the separator:
a ="Hello, World!"
print(a.split(","))# returns ['Hello', ' World!']

Python - String Concatenation


String Concatenation
To concatenate, or combine, two strings you can use the + operator.
A = "Hello"
b = "World"
c = a + b
print(c)
output: HelloWorld
a = "Hello"
b = "World"
c = a + " "+ b
print(c)
output: Hello World
F-Strings
F-String was introduced in Python 3.6, and is now the preferred way of formatting strings.
To specify a string as an f-string, simply put an f in front of the string literal, and add curly
brackets {} as placeholders for variables and other operations.
age = 36
txt = f"My name is John, I am {age}"
print(txt)
output: My name is John, I am 36

 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.

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

Lists are created using square brackets:

Create a List:

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


print(thislist)

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.

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:

ists allow duplicate values:

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


print(thislist)

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

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


print(len(thislist))

List Items - Data Types


List items can be of any data type:

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


list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]

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

Print the second item of the list:

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


print(thislist[1])

Negative Indexing

Negative indexing means start from the end


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

Print the last item of the list:

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


print(thislist[-1])

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.

Return the third, fourth, and fifth item:

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print(thislist[2:5])

Check if Item Exists

To determine if a specified item is present in a list use the in keyword:

Example

Check if "apple" is present in the list:

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


if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")

Change Item Value

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

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


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

Insert Items

To insert a new list item, without replacing any of the existing values, we can use
the insert() method.

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

Example

Insert "watermelon" as the third item:

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


thislist.insert(2, "watermelon")
print(thislist)
Python - Add List Items

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

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


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

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:

Insert an item as the second position:

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


thislist.insert(1, "orange")
print(thislist)
Remove Specified Item

The remove() method removes the specified item.

Remove "banana":

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


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

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)

The pop() method removes the specified index.

Example

Remove the second item:

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


thislist.pop(1)
print(thislist)

he del keyword also removes the specified index:

Example

Remove the first item:

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


del thislist[0]
print(thislist)
he del keyword can also delete the list completely.

Example

Delete the entire list:

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


del thislist

Clear the List

The clear() method empties the list.

The list still remains, but it has no content.

Example

Clear the list content:

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


thislist.clear()
print(thislist)

Sort List Alphanumerically

List objects have a sort() method that will sort the list alphanumerically, ascending, by default:

Sort the list alphabetically:

thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]


thislist.sort()
print(thislist)

Sort the list numerically:

thislist = [100, 50, 65, 82, 23]


thislist.sort()
print(thislist)

List Methods

Python has a set of built-in methods that you can use on lists.

Method Description

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

extend() Add the elements of a list (or any iterable), to the end of the current list

index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list

You might also like