0% found this document useful (0 votes)
4 views10 pages

Unit - 3 Pythhon String and Operators

The document provides an overview of Python strings and operators, explaining the nature of strings, how to create and manipulate them, and various string methods. It covers topics such as string concatenation, slicing, and checking for substrings, as well as different types of operators in Python including arithmetic, assignment, comparison, logical, identity, and membership operators. Additionally, it includes examples and syntax for using these features effectively.

Uploaded by

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

Unit - 3 Pythhon String and Operators

The document provides an overview of Python strings and operators, explaining the nature of strings, how to create and manipulate them, and various string methods. It covers topics such as string concatenation, slicing, and checking for substrings, as well as different types of operators in Python including arithmetic, assignment, comparison, logical, identity, and membership operators. Additionally, it includes examples and syntax for using these features effectively.

Uploaded by

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

Unit3 – Python Strings & Operators

1. What is String in Python?

Python string is the collection of the characters surrounded by single quotes,


double quotes, or triple quotes. The computer does not understand the
characters; internally, it stores manipulated character as the combination of the
0's and 1's.

Each character is encoded in the ASCII or Unicode character. So we can say that
Python strings are also called the collection of Unicode characters.

In Python, strings can be created by enclosing the character or the sequence of


characters in the quotes. Python allows us to use single quotes, double quotes,
or triple quotes to create the string.

2. What is Multiline String In Python?


n Python, a multiline string is a string that spans multiple lines. You can create
multiline strings using triple-quotes, either single (''') or double ("""). This is
particularly useful when you need to represent a block of text, such as a long
paragraph, code snippet, or multi-line comment.

Here's an example of a multiline string using triple-quotes:

multiline_string = '''This is a
multiline
string in Python.
It spans multiple lines.'''

You can also use double triple-quotes (""") for multiline strings:

another_multiline_string = """This is another


multiline
string."""

Multiline strings preserve the line breaks and formatting within them. They are
often used for docstrings (documentation within functions, modules, or
classes), writing SQL queries, or any situation where you need to include
multiple lines of text as a single string.

-1-
Unit3 – Python Strings & Operators

3. String as character array in Python:


• 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.
• Name=input(“enter the name”)
• str=“HELLO”

str = "HELLO"
print(str[0])
print(str[1])
print(str[2])
print(str[3])
print(str[4])
# It returns the IndexError because
6th index doesn't exist
print(str[6])

4. Looping through a String:


• Since strings are arrays, we can loop through the characters in a string,
with a for loop.
• Example:
for x in “python":
print(x)

5. String Length:
• To get the length of a string, we can use the len() function. len()
function returns the length of the string.
-2-
Unit3 – Python Strings & Operators

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

6. Check String:
• To check if a certain phrase or character is present in a string, we can
use the keyword in.
txt = “Python is very interesting subject."
print(“very" in txt)
It will returns true
txt="python is very interesting"
if "very" in txt:
print("very is present in the string")
if “Very" not in txt:
print(“Very is not present in the string")

7. Slicing String:
• 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])
• Get the characters from position 2 to position 5 (5 not included)
• Note: The first character has index 0.

Slice From Start:


• By leaving out the start index, the range will start at the first character:
• b = "Hello,World!"
print(b[:5])
• Get the characters from the start to position 5 (not included)
• b = "Hello,World!"
print(b[:])

-3-
Unit3 – Python Strings & Operators

Slice From End:


• By leaving out the end index, the range will go to the end:
• b = "Hello, World!"
print(b[2:])
• Get the characters from position 2, and all the way to the end:
8. What is Negative Indexing in Python?
• Use negative indexes to start the slice from the end of the string:
• b = "Hello, World!"
print(b[-5:-2])
• Get the characters:
From: "o" in "World!" (position -5)
To, but not included: "d" in "World!" (position -2):

9. What is String Concatenation in Python?


• To concatenate, or combine, two strings you can use the + operator.
• Example:
• a = "Hello"
b = "World"
c=a+b
print(c)
• Output:HelloWorld
• Merge variable a with variable b into variable c:
• To add a space between them, add a " “
• a = "Hello"
b = "World"
c=a+" "+b
print(c)
Output:
Hello World

-4-
Unit3 – Python Strings & Operators

10. Explain various string methods in python:


1. center() :
• Python center() method alligns string to the center by filling
paddings left and right of the string.
• Syntax:center(width[,fillchar])
• This method takes two parameters, first is a width and second is a
fillchar which is optional.
• The fillchar is a character which is used to fill left and right padding
of the string.
• Default value of fillchar is space.
Example:
txt = ”python"
x = txt.center(20)
print(x)
Output:
python

txt = “python"
x = txt.center(20, “#")
print(x)
Output:
#######python#######

2. count() :
• It returns the number of occurences of substring in the specified
range. It takes three parameters, first is a substring, second a start
index and third is last index of the range. Start and end both are
optional whereas substring is required.
• Syntax:count(sub[, start[, end]])
Example:
txt = "Hello world"
c= txt.count(‘l')
print(c)
output:3
txt = “Python is easy.I love Python.python is intresting"
-5-
Unit3 – Python Strings & Operators

c= txt.count(‘Python')
print(c)
output:2

txt = “Python is easy.I love Python.python is intresting"


c= txt.count(‘Python‘,3)
print(c)
output:1
txt = “Python is easy.I love Python.python is intresting"
c= txt.count(‘Python‘,3,10)
print(c)
output:0

3. join() :
This method is used to concat a string with iterable object. It returns a
new string which is the concatenation of the strings in iterable. It throws
an exception TypeError if iterable contains any non-string value.
Example:
myTuple = (“Python”, ”Programming”, “Language”)
x = "#".join(myTuple)
print(x)
Output:
Python#Programming#Language

myList = [“10”, “20”, “30”]


sep=“->”
x = sep.join(myList)
print(x)
Output:10->20->30

4. max() and min() :


max() and min() are inbuilt functions in Python programming language
that returns the highest and lowest alphabetical character
respectively in a string as per the ascii value of character.

-6-
Unit3 – Python Strings & Operators

The smallest possible character is the capital letter A, since all capital
letters come first in Python. Our largest character is the lowercase
letter z.

Example:
x=”python”
print(max(x),min(x))
Output:y,h

5. replace():
Return a copy of the string with all occurrences of
substring old replaced by new.

Syntax:
replace(old, new[, count])

If the optional argument count is given, only the first count occurrences
are replaced.
txt="python is easy .I love python.python is intresting "
y=txt.replace("python","java")
print(y)
Output:
java is easy .I love java.java is intresting

txt="python is easy .I love python.python is intresting "


y=txt.replace("python","java“,2)
print(y)
Output:
java is easy .I love java.python is intresting

-7-
Unit3 – Python Strings & Operators

6. lower() and upper():


Python lower() and upper() methods converts all the characters to
lowercase and uppercase respectively and returns a uppercase and
lowercase string.
Example:
txt=“python”
txt1=txt.upper()
print(txt1)
Output:
PYTHON

txt=“PYTHON”
txt1=txt.lower()
print(txt1)
Output:
python

7. split():
Python split() method splits the string into a comma separated list. It
separates string based on the separator delimiter. This method takes
two parameters and both are optional.
split(sep=None, maxsplit=-1)
• sep: A string parameter acts as a separator.
• maxsplit: Number of times split performs.
Example:
txt="python is easy. i love python. python is interesting"
y=txt.split()
print(y)
['python', 'is', 'easy.', 'i', 'love', 'python.', 'python', 'is', 'interesting']

txt="python is easy. i love python. python is interesting"


y=txt.split(".")
print(y)
[‘python is easy', ' i love python', ' python is interesting']

-8-
Unit3 – Python Strings & Operators

txt="python is easy. i love python. python is interesting.it is programmi


ng language"
y=txt.split(".",2)
print(y)
['python is easy', ' i love python', ' python is interesting.it is
programming language']

11. Operators in Python:


Arithmetic Operators(+,-,*,/,%,**,//)
Assignment Operators(=,+=,-=,/=,*=,//=)
Comparison Operators ( ==, !=, >,<,>=,<=)
Logical Operators ( and, or, not)
identity and membership operators ( is, is not, in, not in)
1. Identity Operators:
➔ is Operator:
This operator checks if two variables refer to the same object. It tests
for object identity.
Example:
x = [1, 2, 3]
y = [1, 2, 3]
print(x is y) # False, as x and y are different objects
➔ is not Operator:
This operator checks if two variables do not refer to the same object.
Example:
x = [1, 2, 3]
y = [1, 2, 3]
print(x is not y) # True, as x and y are different objects
2. Membership Operators:
➔ in Operator:
This operator tests if a value exists in a sequence (such as a string, list,
or tuple).
Example:
my_list = [1, 2, 3, 4]
print(3 in my_list) # True, as 3 is present in the list

-9-
Unit3 – Python Strings & Operators

➔ not in Operator:
This operator tests if a value does not exist in a sequence.
Example:
my_list = [1, 2, 3, 4]
print(5 not in my_list) # True, as 5 is not present in the list

-10-

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy