Notes
Std. : VIII Sub. : Computer Topic : Ch 1 String Python
LEARNING IN THIS CHAPTER???
● Assign String to a variable
● Looping through a String
● String Built-in methods
● Escape characters
String
S tring is a sequence which is made up of oneormoreUNICODEcharacters.Herethecharactercanbea
letter, digit, whitespace or any other symbol.Stringsinpythonaresurroundedbyeithersinglequotation
marks, or double quotation marks.
'hello' is the same as "hello".
You can display a string literal with the print() function:
1.1 Assign String to a variable
Program 1:Assign String to a Variable rogram 2:Assigning a string to a variable is donewith
P
the variable name followed by an equal sign and the
string:
1.1.1 Multiline Strings
Y ou can assign a multiline string to a variable by using three quotes: You can use three double quotes:
Program 3
SGVP International School, Ahmedabad - INDIA 1of12
1.1.2 Three single quotes:
= '''Hello! friends,
a ello! friends,
H
I am learning python since last
I am learning python since last
year,
year,
At present I am learning Python
At present I am learning Python
String
String
along with String methods.'''
along with String methods.
print(a)
1.1.3 Strings are Arrays
L ike 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 singlecharacterissimplya
string with a length of 1. Square brackets can be used to access elements of the string.
Program 4: Get the character at position 1
1.2 Looping Through a String
S ince strings are arrays, we can loop through the characters in a string, with a for loop.
Program 5:
for
x
in"banana"
:
b
print
(x)
a
n
a
n
a
1.2.1 String Length
T o get the length of a string, use the len() function. Thelen()function returns the length of a string:
Program 6:
=
a "Hello, World!" 13
print
(
l
en
(a))
1.2.2 Check String
T o check if a certain phrase or character is present in a string, we can use the keyword in.
Program 7:Check if "free" is present in the followingtext:
xt = "The best things in life are
t True
free!"
print("free" in txt)
Program 8:Use it in an if statement. Print only if"free" is present:
txt = "The best things in life are
Yes, 'free' is present.
SGVP International School, Ahmedabad - INDIA 2of12
ree!"
f
if "free" in txt:
print("Yes, 'free' is present.")
1.2.3 Check if NOT
T o check if a certain phrase or character is NOT present in a string, we can use the keyword not in.
Program 9:Check if "expensive" is NOT present inthe following text:
xt =
t "The best things in life are
True
free!"
print
(
"expensive"
not
in
txt)
Use it in an if statement:
xt =
t "The best things in life are
No, 'expensive' is NOT present.
free!"
if
"expensive"not
in
txt:
print
(
"No, 'expensive' is NOT
present."
)
1.2.4 Slicing
Y ou 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.
Program 10:Get the characters from position 2 toposition 5 (not included):
=
b "Hello, World!" llo
print
(b[
2
:
5
])
Note:
The first character has index 0.
1.2.5 Slice From the Start
y leaving out the start index, the range will start at the first character:
B
Program 11:Get the characters from the start to position5 (not included):
=
b "Hello, World!" Hello
print
(b[:
5
])
1.2.6 Slice To the End
y leaving out the end index, the range will go to the end:
B
Program 12: Get the characters from position 2, andall the way to the end:
=
b "Hello, World!" llo, World!
print
(b[
2
:])
1.2.7 Negative Indexing
se negative indexes to start the slice from the end of the string:
U
Program 13: Get the characters:
From: "o" in "World!" (position -5)
To, but not included: "d" in "World!" (position -2):
=
b "Hello, World!" orl
print
(b[-
5
:-
2
])
1.3 String Built-in Methods
ython has a set of built-in methods that you can use on strings.
P
Upper Case :The upper() method returns the stringin upper case:
SGVP International School, Ahmedabad - INDIA 3of12
Program 14:
=
a "Hello, World!" HELLO, WORLD!
print
(a.upper())
L ower Case :The lower() method returns the stringin lower case:
Program 15:
=
a "Hello, World!" hello, world!
print
(a.lower())
emove Whitespace
R
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 whitespace from the beginning or the end:
Program 16:
=
a " Hello, World! " Hello, World!
print
(a.strip())
# returns "Hello,
World!"
eplace String:The replace() method replaces a stringwith another string:
R
Program 17:
=
a "Hello, World!" Jello, World!
print
(a.replace(
"H"
,
"J"
))
S plit String
The split() method returns a list where the text between the specified separator becomes the list items.
Program 18:The split() method splits the string intosubstrings if it finds instances of the separator
=
a "Hello, World!" ['Hello', ' World!']
print
(a.split(
","
))
# returns
['Hello', ' World!']
S tring Concatenation
To concatenate, or combine, two strings you can use the + operator.
Program 19:Merge variable a with variable b intovariable c:
=
a "Hello" HelloWorld
b =
"World"
c = a + b
print
(c)
Program 20:To add a space between them, add a " ":
=
a "Hello" Hello World
b =
"World"
c = a +
" "
+ b
print
(c)
.3.7 String Format
2
We cannot combine strings and numbers like this:
Program 21:
ge =
a 36 Traceback (most recent call last):
txt =
"My name is John, I am "
+ File
age
"demo_string_format_error.py",
print
(txt)
line 2, in <module>
txt = "My name is John, I am "
SGVP International School, Ahmedabad - INDIA 4of12
age
+
TypeError: must be str, not int
ut we can combine strings and numbers by using the format() method!
B
The format() method takes the passed arguments, formats them, and places them in the string where the
placeholders {} are:
Program 22:Use the format() method to insert numbersinto strings:
ge =
a 36 My name is John, and I am 36
txt =
"My name is John, and I am
{}"
print
(txt.
format
(age))
T he format() method takes unlimited number of arguments, and are placed into the respective
placeholders:
uantity =
q 3 want 3 pieces of item 567 for
I
itemno =
567 49.95 dollars.
price =
49.95
myorder =
"I want {} pieces of
item {} for {} dollars."
print
(myorder.
format
(quantity,
itemno, price))
You can use index numbers {0} to be sure the arguments are placed in the correct placeholders:
uantity =
q 3 want to pay 49.95 dollars for 3
I
itemno =
567 pieces of item 567
price =
49.95
myorder =
"I want to pay {2}
dollars for {0} pieces of item
{1}."
print
(myorder.
format
(quantity,
itemno, price))
ote:All string methods return new values. They donot change the original string.
N
capitalize():The capitalize() method returns a stringwhere the first character is upper case, and the rest is
lower case.
Syntax: string.capitalize()
xt =
t "hello, and welcome to my Hello, and welcome to my world.
world."
x = txt.capitalize()
print
(x)
xt =
t "python is FUN!" Python is fun!
x = txt.capitalize()
print
(x)
xt =
t "36 is my Age." 36 is my age.
x = txt.capitalize()
print
(x)
c asefold():The casefold() method returns a stringwhere all the characters are lower case.This method is
similar to the lower() method, but the casefold() method is stronger, more aggressive, meaning that it will
SGVP International School, Ahmedabad - INDIA 5of12
c onvert more characters into lower case, and will find more matches when comparing two strings and both
are converted using the casefold() method.
Syntax: string.casefold()
xt =
t "Hello, And Welcome To My hello, and welcome to my world!
World!"
x = txt.casefold()
print
(x)
c enter():The center() method will center align thestring, using a specified character (space is default) as
the fill character.
Syntax: string.center(length, character)
xt =
t "banana" banana
x = txt.center(
20
)
print
(x)
xt =
t "banana" OOOOOOObananaOOOOOOO
x = txt.center(
20
,
"O"
)
print
(x)
c ount():The count() method returns the number oftimes a specified value appears in the string.
Syntax: string.count(value, start, end)
xt =
t "I love apples, apple are my
2
favorite fruit"
x = txt.count(
"apple"
)
print
(x)
Search from position 10 to 24:
xt =
t "I love apples, apple are my 1
favorite fruit"
x = txt.count(
"apple"
,
10
,
24
)
print
(x)
islower():The islower() method returns True if allthe characters are in lower case, otherwise False.
Numbers, symbols and spaces are not checked, only alphabet characters.
Syntax: string.islower()
=
a "Hello world!" alse
F
b =
"hello 123" True
c =
"mynameisPeter" False
rint
p (a.islower())
print
(b.islower())
print
(c.islower())
r eplace():The replace() method replaces a specifiedphrase with another specified phrase.
Syntax: string.replace(oldvalue, newvalue, count)
Program to Replace all occurrence of the word "one":
xt =
t "one one was a race horse, hree three was a race horse, two
t
two two was one too."
two was three too."
x = txt.replace(
"one"
,
"three"
)
print
(x)
SGVP International School, Ahmedabad - INDIA 6of12
Program to Replace the two first occurrence of the word "one":
xt =
t "one one was a race horse, hree three was a race horse, two
t
two two was one too."
two was one too."
x = txt.replace(
"one"
,
"three"
,
2
)
print
(x)
s wapcase(): The swapcase() method returns a string where all the uppercaselettersarelowercaseand
vice versa.
Program to make the lower case letters uppercase and the upper case letters lower case:
xt =
t "Hello My Name Is PETER" hELLO mY nAME iS peter
x = txt.swapcase()
print
(x)
1.4 Escape Character
T o insert characters that are illegal in a string, use an escape character.
An escape character is a backslash \ followed by the character you want to insert.
An example of an illegal character is a double quote inside a string that is surrounded by double quotes:
You will get an error if you use double quotes inside a string that is surrounded by double quotes:
xt =
t "We are the so-called File
"
Vikings
" from the north."
demo_string_escape_error.py",
"
line 1
txt = "We are the so-called
"Vikings" from the north."
^
SyntaxError: invalid syntax
T o fix this problem, use the escape character \":
The escape character allows you to use double quotes when you normally would not be allowed:
xt =
t "We are the so-called e are the so-called "Vikings"
W
\"
Vikings\
" from the north."
from the north.
E scape Characters
Other escape characters used in Python:
Code Result Try it Output
\' Single Quote xt = 'It\'s alright.'
t It's alright.
print(txt)
\\ Backslash xt = "This will insert
t his will insert one \
T
one \\ (backslash)."
(backslash).
print(txt)
\n New Line xt = "Hello\nWorld!"
t ello
H
print(txt)
World!
\t Tab xt = "Hello\tWorld!"
t Hello
World!
print(txt)
\b Backspace This example erases one
# HelloWorld!
character (backspace):
txt = "Hello \bWorld!"
print(txt)
SGVP International School, Ahmedabad - INDIA 7of12
EXERCISE
Q : A C
hoose the correct option
1. Guess the correct output of the following String operations
str1 = 'Welcome'
print(str1*2)
(a) WelcomeWelcome (b) Welcome Welcome
(c) WelcomWelcome (d) WelcomWelcom
2. Select the correct output of the following String operations
str1 = 'Welcome'
print (str1[:6] + ' PYnative')
(a) Welcome PYnative (b) WelcomPYnative
(c) Welcom PYnative (d) WelcomePYnative
3. Which method should be use to convert String "welcome to the beautiful world of python" to
"Welcome to the beautiful world of python"
(a) capitalize() (b) title() (c) upper (d) isupper
4. Select the correct output of the following String operations
str = "my name is James bond";
print (str.capitalize())
(a) My Name Is James Bond
(b) TypeError: unsupported operand type(s) for * orpow(): 'str' and 'int'
(c) My name is james bond
(d) My name is James Bond
5. What is the output of the following code
str1 = "My salary is 7000";
str2 = "7000"
print(str1.isdigit())
print(str2.isdigit())
(a) False / True (b) True / True (c) True / False (d) False / False
Q : B S tate whether the statements are True or False
1. Strings are immutable in Python, which means a string cannot be modified.
2. Python does not support a character type; a single character is treated as strings of length
one.
3. The islower() method converts all the characters in lower case.
4. To concatenate, or combine, two strings you can use the+operator.
5. To get the length of a string, use the length() function.
Q : C Answer the following questions
1. What is a String in python?
2. State the difference between count() and len() function.
3. Name few built-in methods to modify Strings.
Q : D W
rite the output for the following code
1. str = "geeks"
print(len(str))
2. name = "geeks FOR geeks"
print(name.capitalize())
3. string = "geeks for geeks"
print(string.count("geeks"))
Upper counts 3
Special counts 2
SGVP International School, Ahmedabad - INDIA 8of12
SGVP International School, Ahmedabad - INDIA 9of12