0% found this document useful (0 votes)
22 views

UNIT-3Strings in Python

Uploaded by

mradulmishra2005
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

UNIT-3Strings in Python

Uploaded by

mradulmishra2005
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

Strings in Python

A string is a sequence of characters that can be a combination of letters, numbers, and


special characters. It can be declared in python by using single quotes, double quotes, or
even triple quotes. These quotes are not a part of a string, they define only starting and
ending of the string. Strings are immutable, i.e., they cannot be changed. Each element of
the string can be accessed using indexing or slicing operations.
Code

# Assigning string to a variable


a = 'This is a string'
print (a)
b = "This is a string"
print (b)
c= '''This is a string'''
print (c)

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

tup = (1, "a", "string", 1+2)


print(tup)
print(tup[1])

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

The output is:


1
2
3
4
5
6
7
8
9

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)

The output is:


1
4
5
7
8
9

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

Strings in Python are sequences of characters, so we can access individual characters


using indexing. Strings are indexed starting from 0 and -1 from end. This allows us to
retrieve specific characters from the string.

Python String syntax indexing

Code
s = "GeeksforGeeks"

# Accesses first character: 'G'


print(s[0])

# Accesses 5th character: 's'


print(s[4])
1

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"

# Accesses 3rd character: 'k'


print(s[-10])

# Accesses 5th character from end: 'G'


print(s[-5])

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])

# Retrieves characters from beginning to index 2: 'Gee'


print(s[:3])

# Retrieves characters from index 3 to the end: 'ksforGeeks'


print(s[3:])

# 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"

# Trying to change the first character raises an error


# s[0] = 'I' # Uncommenting this line will cause a TypeError

# Instead, create a new string


s = "G" + s[1:]
print(s)

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

upper() and lower(): upper() method converts all characters to uppercase.


lower() method converts all characters to lowercase.

Code
1

s = "Hello World"

print(s.upper()) # output: HELLO WORLD

print(s.lower()) # output: hello world

strip() and replace(): strip() removes leading and trailing


whitespace from the string and replace(old, new) replaces all
occurrences of a specified substring with another.
Code
1

s = " Gfg "


# Removes spaces from both ends
print(s.strip())
s = "Python is fun"
# Replaces 'fun' with 'awesome'
print(s.replace("fun", "awesome"))
Output
Gfg
Python is awesome

Concatenating and Repeating Strings

We can concatenate strings using + operator and repeat them


using * operator.
Strings can be combined by using + operator.
Code
s1 = "Hello"
s2 = "World"
s3 = s1 + " " + s2
print(s3)

Output
Hello World
We can repeat a string multiple times using * operator.

Code
s = "Hello "
print(s * 3)
Output
Hello Hello Hello

Formatting Strings

Python provides several ways to include variables inside strings.


Using f-strings
The simplest and most preferred way to format strings is by using f-
strings.
Code

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

s = "My name is {} and I am {} years old.".format("Alice", 22)

print(s)

Output
My name is Alice and I am 22 years old.

Using in for String Membership Testing

The in keyword checks if a particular substring is present in a string.


Python

Code

s = "GeeksforGeeks"

print("Geeks" in s)

print("GfG" in s)
Output
True
False

Python String Methods

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.

Case Changing of Python String Methods

The below Python functions are used to change the case of the strings. Let’s look at some
Python string methods with examples:

 lower(): Converts all uppercase characters in a string into lowercase


 upper(): Converts all lowercase characters in a string into uppercase
 title(): Convert string to title case
 swapcase(): Swap the cases of all characters in a string
 capitalize(): Convert the first character of a string to uppercase
Example:
Changing the case of Python String Methods
Code
# Python3 program to show the
# working of upper() function
text = 'geeKs For geEkS'

# upper() function to convert


# string to upper case
print("\nConverted String:")
print(text.upper())

# lower() function to convert


# string to lower case
print("\nConverted String:")
print(text.lower())

# converts the first character to


# upper case and rest to lower case
print("\nConverted String:")
print(text.title())

# swaps the case of all characters in the string


# upper case character to lowercase and viceversa
print("\nConverted String:")
print(text.swapcase())

# convert the first character of a string to uppercase


print("\nConverted String:")
print(text.capitalize())

# original string never changes


print("\nOriginal String")
print(text)

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

List of String Methods in Python


Here is the list of in-built Python string methods, that you can use to perform actions on
string:
Function Name Description

Converts the first character of the string to


capitalize()
a capital (uppercase) letter

casefold() Implements caseless string matching

center() Pad the string with the specified character.

Returns the number of occurrences of a


count()
substring in the string.

Encodes strings with the specified


encode()
encoded scheme

Returns “True” if a string ends with the


endswith()
given suffix

Specifies the amount of space to be


expandtabs() substituted with the “\t” symbol in the
string

Returns the lowest index of the substring


find()
if it is found

Formats the string for printing it to


format()
console
Function Name Description

Formats specified values in a string using


format_map()
a dictionary

Returns the position of the first occurrence


index()
of a substring in a string

Checks whether all the characters in a


isalnum()
given string is alphanumeric or not

Returns “True” if all characters in the


isalpha()
string are alphabets

Returns true if all characters in a string are


isdecimal()
decimal

Returns “True” if all characters in the


isdigit()
string are digits

Check whether a string is a valid identifier


isidentifier()
or not

Checks if all characters in the string are


islower()
lowercase

Returns “True” if all characters in the


isnumeric()
string are numeric characters

Returns “True” if all characters in the


isprintable()
string are printable or the string is empty

Returns “True” if all characters in the


isspace()
string are whitespace characters
Function Name Description

Returns “True” if the string is a title cased


istitle()
string

Checks if all characters in the string are


isupper()
uppercase

join() Returns a concatenated String

Left aligns the string according


ljust()
to the width specified

Converts all uppercase


lower() characters in a string into
lowercase

Returns the string with leading


lstrip()
characters removed

maketrans() Returns a translation table

Splits the string at the first


partition()
occurrence of the separator

Replaces all occurrences of a


replace()
substring with another substring

Returns the highest index of the


rfind()
substring

Returns the highest index of the


rindex()
substring inside the string
Function Name Description

Right aligns the string according


rjust()
to the width specified

Split the given string into three


rpartition()
parts

Split the string from the right by


rsplit()
the specified separator

rstrip() Removes trailing characters

splitlines() Split the lines at line boundaries

Returns “True” if a string starts


startswith()
with the given prefix

Returns the string with both


strip()
leading and trailing characters

Converts all uppercase


swapcase() characters to lowercase and vice
versa

title() Convert string to title case

Modify string according to given


translate()
translation mappings

Converts all lowercase


upper() characters in a string into
uppercase
Function Name Description

Returns a copy of the string with


zfill() ‘0’ characters padded to the left
side of the string

Note: For more information about Python Strings, refer to Python String Tutorial.

Slicing with Negative Numbers in Python



Slicing is an essential concept in Python, it allows programmers to access parts of sequences
such as strings, lists, and tuples. In this article, we will learn how to perform slicing with
negative indexing in Python.

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.

Slicing with Negative Numbers in Python


In Python, we can perform slicing on iterable objects in two ways first is using list slicing and
the second is using slice() function. Python also allows programmers to slice the iterable
objects using negative indexing. Let's first see the syntax of both methods.
 Using Slicing ( : )
 Using slice() Function

Slicing with Negative Numbers Using Colon ':' Operator


We can perform slicing in Python using the colon ':' operator. It accepts three parameters
which are start, end, and step. Start and end can be any valid index whether it is negative or
positive. When we write step as -1 it will reverse the slice.
Code

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.

Slicing with Negative Numbers Using slice() Function


slice() function is used same as colon ':' operator. In slice() function we passed the start, stop,
and step arguments without using colon.
In this example, a string is stored in the variable "text," and the `slice()` function is employed
for string slicing. For the left part, an empty start indicates slicing from the beginning up to
the index "-8," stored in the variable "left." The middle part is sliced by specifying indices -8
and -5. Similarly, the right part is obtained using the `slice()` function.
code
text = &quot;GeeksforGeeks&quot;
# Slicing left part of string text
left = text[slice(-8)]
# Slicing middle part of string text
middle = text[slice(-8,-5)]
# Slicing right part of string text
right = text[slice(-5,None)]
print(left)
print(middle)
print(right)
Output
Geeks
for
Geeks

String capitalize() Method in Python


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


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.

Example 1: center() Method With Default fillchar

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)

# here fillchar not provided so takes space by default.


print("After padding String is: ", new_string)

Output:
After padding String is: geeks for geeks

Example 2: center() Method With ‘#’ as fillchar

Code

string = "geeks for geeks"


new_string = string.center(24, '#')
# here fillchar is provided
print("After padding String is:", new_string)

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

Python String count() Method



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

You might also like