UNIT-3Strings in Python
UNIT-3Strings in Python
Output:
This is a string
This is a string
This is a string
Lists in Python
Lists are one of the most powerful data structures in python. Lists are sequenced data types.
In Python, an empty list is created using list() function. They are just like the arrays
declared in other languages. But the most powerful thing is that list need not be always
homogeneous. A single list can contain strings, integers, as well as other objects. Lists can
also be used for implementing stacks and queues. Lists are mutable, i.e., they can be altered
once declared. The elements of list can be accessed using indexing and slicing operations.
Code
# Declaring a list
L = [1, "a" , "string" , 1+2]
print L
#Adding an element in the list
L.append(6)
print L
#Deleting last element from a list
L.pop()
print (L)
#Displaying Second element of the list
print (L[1])
Output
[1, 'a', 'string', 3]
[1, 'a', 'string', 3, 6]
[1, 'a', 'string', 3]
a
Tuples in Python
A tuple is a sequence of immutable Python objects. Tuples are just like lists with the
exception that tuples cannot be changed once declared. Tuples are usually faster than lists.
Code
Output
(1, 'a', 'string', 3)
a
Iterations in Python
Iterations or looping can be performed in python by ‘for’ and ‘while’ loops. Apart from
iterating upon a particular condition, we can also iterate on strings, lists, and tuples.
Example 1:
Iteration by while loop for a condition
Code
i=1
while (i < 10):
print(i)
i += 1
Example 2:
Iteration by for loop on the string
Code
s = "Hello World"
for i in s:
print(i)
Output
H
e
l
l
o
W
o
r
l
d
Example 3:
Iteration by for loop on list
Code
L = [1, 4, 5, 7, 8, 9]
for i in L:
print(i)
Example 4:
Iteration by for loop for range
Code
for i in range(0, 10):
print(i)
Output
0
1
2
3
4
5
6
7
8
9
Python String
A string is a sequence of characters. Python treats anything inside quotes as a string. This
includes letters, numbers, and symbols. Python has no character data type so single character
is a string of length 1.
Table of Content
Creating a String
Accessing characters in Python String
String Immutability
Deleting a String
Updating a String
Common String Methods
Concatenating and Repeating Strings
Formatting Strings
Creating a String
Strings can be created using either single (‘) or double (“) quotes.
Code
s1 = 'GfG'
s2 = "GfG"
print(s1)
print(s2)
Output
GfG
GfG
Multi-line Strings
If we need a string to span multiple lines then we can use triple quotes (”’ or “””).
Code
s = """I am Learning
Python String on GeeksforGeeks"""
print(s)
s = '''I'm a
Geek'''
print(s)
1
Output
I am Learning
Python String on GeeksforGeeks
I'm a
Geek
Accessing characters in Python String
Code
s = "GeeksforGeeks"
Output
G
s
Note: Accessing an index out of range will cause an IndexError. Only integers are
allowed as indices and using a float or other types will result in a TypeError.
Access string with Negative Indexing
Python allows negative address references to access characters from back of the String, e.g.
-1 refers to the last character, -2 refers to the second last character, and so on.
Code
s = "GeeksforGeeks"
Output
k
G
String Slicing
Slicing is a way to extract portion of a string by specifying the start and end indexes. The
syntax for slicing is string[start:end], where start starting index and end is stopping index
(excluded).
Code
s = "GeeksforGeeks"
# Retrieves characters from index 1 to 3: 'eek'
print(s[1:4])
# Reverse a string
print(s[::-1])
Output
eek
Gee
ksforGeeks
skeeGrofskeeG
String Immutability
Strings in Python are immutable. This means that they cannot be changed after they are
created. If we need to manipulate strings then we can use methods like concatenation,
slicing, or formatting to create new strings based on the original.
Code
s = "geeksforGeeks"
Output
GeeksforGeeks
Deleting a String
In Python, it is not possible to delete individual characters from a string since strings are
immutable. However, we can delete an entire string variable using the del keyword.
Code
s = "GfG"
# Deletes entire string
del s
1
Note: After deleting the string using del and if we try to access s then it will result in
a NameError because the variable no longer exists.
Updating a String
To update a part of a string we need to create a new string since strings are immutable.
Code
s = "hello geeks"
# Updating by creating a new string
s1 = "H" + s[1:]
# replacnig "geeks" with "GeeksforGeeks"
s2 = s.replace("geeks", "GeeksforGeeks")
print(s1)
print(s2)
Output
Hello geeks
hello GeeksforGeeks
Explanation:
For s1, The original string s is sliced from index 1 to end of string and then
concatenate “H” to create a new string s1.
For s2, we can created a new string s2 and used replace() method to replace
‘geeks’ with ‘GeeksforGeeks’.
String Methods
Python provides a various built-in methods to manipulate strings. Below are some of the
most useful methods.
len(): The len() function returns the total number of characters in a string.
Code
s = "GeeksforGeeks"
print(len(s))
Output: 13
Code
1
s = "Hello World"
Output
Hello World
We can repeat a string multiple times using * operator.
Code
s = "Hello "
print(s * 3)
Output
Hello Hello Hello
Formatting Strings
name = "Alice"
age = 22
print(f"Name: {name}, Age: {age}")
Output
Name: Alice, Age: 22
Using format()
Another way to format strings is by using format() method.
Python
Code
print(s)
Output
My name is Alice and I am 22 years old.
Code
s = "GeeksforGeeks"
print("Geeks" in s)
print("GfG" in s)
Output
True
False
Python string methods is a collection of in-built Python functions that operates on lists.
Note: Every string method in Python does not change the original string instead returns a new
string with the changed attributes.
Python string is a sequence of Unicode characters that is enclosed in quotation marks. In this
article, we will discuss the in-built string functions i.e. the functions provided by Python to
operate on strings.
The below Python functions are used to change the case of the strings. Let’s look at some
Python string methods with examples:
Output
Converted String:
GEEKS FOR GEEKS
Converted String:
geeks for geeks
Converted String:
Geeks For Geeks
Converted String:
GEEkS fOR GEeKs
Original String
geeKs For geEkS
Note: For more information about Python Strings, refer to Python String Tutorial.
Indexing in Python
In the world of programming, indexing starts at 0, and Python also follows 0-indexing what
makes Python different is that Python also follows negative indexing which starts from -1. -1
denotes the last index, -2, denotes the second last index, -3 denotes the third last index, and so
on.
text = "GeeksforGeeks"
# Slicing left part of string text
left = text[:-8]
# Slicing middle part of string text
middle = text[-8:-5]
# Slicing right part of string text
right = text[-5:]
print(left)
print(middle)
print(right)
Output
Geeks
for
Geeks
In this example, we use the variable "text" to demonstrate string slicing. Slicing
from the left starts from the beginning, and for the middle part, we specify indices.
The right part is sliced similarly. The slices are stored in variables "left," "middle,"
and "right" respectively.
Syntax:
sequence[Start : End : Step]
Parameters:
Start: It is the starting point of the slice or substring.
End: It is the ending point of the slice or substring but it does not include the last
index.
Step: It is number of steps it takes.
The capitalize() method in Python is used to change the first letter of a string to uppercase
and make all other letters lowercase. It is especially useful when we want to ensure that text
follows title-like capitalization, where only the first letter is capitalized.
Let’s start with a simple example to understand the capitalize() functions:
Code
s = "hello WORLD"
res = s.capitalize()
print(res)
Output
Hello world
Python String center() method creates and returns a new string that is padded with the
specified character.
Syntax: string.center(length[, fillchar])
Parameters:
length: length of the string after padding with the characters.
fillchar: (optional) characters which need to be padded. If it’s not provided, space
is taken as the default argument.
Returns: Returns a string padded with specified fillchar and it doesn’t modify the original
string.
Python String center() Method tries to keep the new string length equal to the given length
value and fills the extra characters using the default character (space in this case).
Code
string = "geeks for geeks"
new_string = string.center(24)
Output:
After padding String is: geeks for geeks
Code
Output:
After padding String is: ####geeks for geeks#####
Example 3: center() Method with length argument value less than original
String length
Code
string = "GeeksForGeeks"
# new string will be unchanged
print(string.center(5))
Output:
GeeksForGeeks
The count() method in Python returns the number of times a
specified substring appears in a string. It is commonly used in
string analysis to quickly check how often certain characters or
words appear.
Let’s start with a simple example of using count().
Code
s = "hello world"
res = s.count("o")
print(res)
Output
2