Programming and Problem Solving through Python
String in Python
Introguction
A string is any series of characters that are interpreted literally by Python. For
example, "hello world" and "LKJH019283#" are both examples of strings.
String Literals:
String literals in python are surrounded by either single quotation marks, or double
quotation marks, i.e., 'hello' is the same as "hello". You can display a string literal
with the print() function. For example:
print("Hello")
print('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. For example:
a = "Hello"
print(a)
Multiline Strings
You can assign a multiline string to a variable by using three quotes. For example:
You can use three double quotes:
a = """Current month is January,
This is third week ,
Today is Monday
and this is seond day of week."""
print(a)
Or three single quotes:
a='''Current month is January,
This is third week ,
Today is Monday
and this is seond day of week.'''
print(a)
String Indexing:
Strings in Python are sequence 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. An integer index (0 base) within a pair of square brackets([])
can be used to access elements of the string. For example to get the second
character, i.e., character at position 1 (remember that the first character has the
position 0):
a = "Hello, World!"
print(a[1])
String Slicing:
You can return a range of characters by using the slice syntax. In slice specify the
start index and the end index, separated by a colon, to return a part of the string.
For example to get the characters from position 2 to position 5 (not included):
Page - 1
Programming and Problem Solving through Python
b = "Hello, World!"
print(b[2:5])
Negative indexes can be used to start the slice from the end of the string. To get
the characters from position 5 to position 1, starting the count from the end of the
string:
b = "Hello, World!"
print(b[-5:-2])
N.B.: Here the right-most character is at -1.
String Length:
To get the length of a string, the len() function is used. For example:
a = "Hello, World!"
print(len(a))
The len() function returns the length of a string:
Loop Through String
You can loop through the string by using a for loop:
fruit = "apple"
for x in fruit:
print(x)
You can also use while loop to access characters of a string:
fruit = "apple"
i=0
while i<l en(fruit):
print(fruit[i])
i+=1
String Concatenation:
To concatenate, or combine, two string sthe + operator can be used. For example
to concatenate variable a with variable b into variable c:
a = "Hello"
b = "World"
c=a+b
print(c)
Checking substring in a String:
To check if a certain phrase or character is present in a string, we can use the
keywords in or not in. for example to Check if the phrase "ain" is present in the
following text:
txt = "The rain in Spain stays mainly in the plain"
x = "ain" in txt
print(x)
To check if the phrase "ain" is NOT present in the following text:
Page - 2
Programming and Problem Solving through Python
txt = "The rain in Spain stays mainly in the plain"
x = "ain" not in txt
print(x)
String Methods:
Python has a set of built-in methods that can be used on strings.
Sl. Method Description Example
No.
1. capitalize() Converts the first character to str="hello"
upper case print([Link]())
2. count(substr) Returns the number of times str="Hello World"
a specified value occurs in a print([Link]('o'))
string
3. endswith(substr) Returns true if the string ends str="Hello World"
with the specified value print([Link]('ld'))
4. find(substr) Searches the string for a str="welcome"
specified value and returns print([Link]('e'))
the position of where it was
found (-1 if unsuccessfull)
5. index(substr) Searches the string for a str="welcome"
specified value and returns print([Link]('e'))
the position of where it was
found
6. isalnum() Returns True if all characters code="M3R5"
in the string are print([Link]())
alphanumeric
7 isalpha() Returns True if all characters str="hello"
in the string are in the print([Link]())
alphabet
8. isdigit() Returns True if all characters str="105"
in the string are digits print([Link]())
9. islower() Returns True if all characters str="hello"
in the string are lower case print([Link]())
10. isspace() Returns True if all characters str=" "
in the string are whitespaces print([Link]())
11. isupper() Returns True if all characters str="HELLO"
Page - 3
Programming and Problem Solving through Python
in the string are upper case print([Link]())
12. join(iterable) Joins the elements of an sep=", "
iterable separated by the list=["Hello","World"]
string str=[Link](list)
print(str)
13. lower() Converts a string into lower a="Hello World!"
case rint([Link]())
14. lstrip() Returns a left trim version of a = " Hello, World"
the string print([Link]())
15. partition(separator) Returns a tuple where the a="This is a cat"
string is parted into three t=[Link](" ")
parts print(t)
16. replace(s1,s2) Returns a string where a a = "Hello, World!"
specified value is replaced print([Link]("H", "J"))
with a specified value
17. rfind(substr) Searches the string for a a="element"
specified value and returns print([Link]('e'))
the last position of where it
was found
18. rindex(substr) Searches the string for a a="element"
specified value and returns print([Link]('e'))
the last position of where it
was found
19. rstrip() Returns a right trim version a="Hello, World! "
of the string print([Link]())
20. split(separator) Splits the string at the a = "This is a cat"
specified separator, and l= [Link](" ")
returns a list print(l)
21. splitlines() Splits the string at line breaks a="""This is a cat
and returns a list This is a tiger
"""
l= [Link]()
print(l)
22. startswith(substr) Returns true if the string a="Hello World"
starts with the specified value print([Link]("H"))
Page - 4
Programming and Problem Solving through Python
23. strip() Returns a trimmed version of a=" Hello, World! "
the string print([Link]())
24. swapcase() Swaps cases, lower case a=" Hello, World! "
becomes upper case and vice print([Link]())
versa
25. title() Converts a string into title a = "hello,wWorld!"
case print([Link]())
26. upper() Converts a string into upper a = "Hello, World!"
case print([Link]())
String Format:
1. Using format() method
The format() method takes the passed arguments, formats them, and places them
in the string at the position of placeholders {}. For example, the format() method
can be used to insert numbers into strings:
a=36
txt = "My name is John, and I am {}"
print([Link](a))
The format() method takes unlimited number of arguments, and are placed into the
respective placeholders: for example:
itemn = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print([Link](quantity, itemn, price))
The format() method can also be used in the following way:
name="John"
age=36
txt="{x} is {y} years old".format(x=name, y=age)
print(txt)
2. Without using format() methos
In Python string can be formatted without using format() method alsoas shown
below:
a) Using format specifier:
#formatting string value
name="Amit"
s="Hello, %s"% name
print(s)
#Formatting integer
name="Amit"
age=21
s=" %s is %d years old"%(name,age)
Page - 5
Programming and Problem Solving through Python
print(s)
#formatting float value
a=3.142857
s1="a=%f"%a
print(s1)
s2="a=%.3f"%a
print(s2)
b) Using string interpolation (Supported by Python 3.6+)
name="Amit"
age=22
s=f"{name} is {age} years old"
print(s)
Escape Characters:
An escape character is a backslash \ followed by a character which carries a special
meaning for Python:
An example of an escape character is a double quote inside a string. The escape
character allows you to use double quotes when you normally would not be
allowed:
txt = "Hello, \"World!\" "
Other escape characters used in Python:
Code Result
\' Single Quote
\" Double Quote
\\ Backslash
\n New Line
\t Tab
\b Backspace
\ooo (\octal-val) Octal value
\xhh (\xhex-val) Hex value
Page - 6