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

Practical 4 String

Uploaded by

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

Practical 4 String

Uploaded by

SK Roy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Practical 4

Deleting/Updating from a String


In Python, the Updation or deletion of characters from a String is not allowed.
This will cause an error because item assignment or item deletion from a String
is not supported. Although deletion of the entire String is possible with the use of
a built-in del keyword. This is because Strings are immutable, hence elements of
a String cannot be changed once assigned. Only new strings can be reassigned to
the same name.
Updating a character
A character of a string can be updated in Python by first converting the string
into a Python List and then updating the element in the list. As lists are mutable
in nature, we can update the character and then convert the list back into the
String.
Another method is using the string slicing method. Slice the string before the
character you want to update, then add the new character and finally add the
other part of the string again by string slicing.
Example:
In this example, we are using both the list and the string slicing method to update
a character. We converted the String1 to a list, changes its value at a particular
element, and then converted it back to a string using the Python string
join() method.
In the string-slicing method, we sliced the string up to the character we want to
update, concatenated the new character, and finally concatenate the remaining
part of the string.
 Python3

# Python Program to Update

# character of a String

String1 ="Hello, I'm a Geek"

print("Initial String: ")

print(String1)

1|Page
# Updating a character of the String

## As python strings are immutable, they don't support item updation directly

### there are following two ways

#1

list1 =list(String1)

list1[2] ='p'

String2 =''.join(list1)

print("\nUpdating character at 2nd Index: ")

print(String2)

#2

String3 =String1[0:2] +'p'+String1[3:]

print(String3)

Output:
Initial String:
Hello, I'm a Geek
Updating character at 2nd Index:
Heplo, I'm a Geek
Heplo, I'm a Geek
Updating Entire String
As Python strings are immutable in nature, we cannot update the existing string.
We can only assign a completely new value to the variable with the same name.
Example:
In this example, we first assign a value to ‘String1’ and then updated it by
assigning a completely different value to it. We simply changed its reference.
 Python3

2|Page
# Python Program to Update

# entire String

String1 ="Hello, I'm a Geek"

print("Initial String: ")

print(String1)

# Updating a String

String1 ="Welcome to the Geek World"

print("\nUpdated String: ")

print(String1)

Output:
Initial String:
Hello, I'm a Geek
Updated String:
Welcome to the Geek World
Deleting a character
Python strings are immutable, that means we cannot delete a character from it.
When we try to delete thecharacter using the del keyword, it will generate an
error.
 Python3

# Python Program to delete

# character of a String

3|Page
String1 ="Hello, I'm a Geek"

print("Initial String: ")

print(String1)

print("Deleting character at 2nd Index: ")

delString1[2]

print(String1)

Output:
Initial String:
Hello, I'm a Geek
Deleting character at 2nd Index:
Traceback (most recent call last):
File "e:\GFG\Python codes\Codes\demo.py", line 9, in <module>
del String1[2]
TypeError: 'str' object doesn't support item deletion
But using slicing we can remove the character from the original string and store
the result in a new string.
Example:
In this example, we will first slice the string up to the character that we want to
delete and then concatenate the remaining string next from the deleted
character.
 Python3

# Python Program to Delete

# characters from a String

String1 ="Hello, I'm a Geek"

print("Initial String: ")

print(String1)

4|Page
# Deleting a character

# of the String

String2 =String1[0:2] +String1[3:]

print("\nDeleting character at 2nd Index: ")

print(String2)

Output:
Initial String:
Hello, I'm a Geek
Deleting character at 2nd Index:
Helo, I'm a Geek
Deleting Entire String
Deletion of the entire string is possible with the use of del keyword. Further, if
we try to print the string, this will produce an error because the String is deleted
and is unavailable to be printed.
 Python3

# Python Program to Delete

# entire String

String1 ="Hello, I'm a Geek"

print("Initial String: ")

print(String1)

# Deleting a String

# with the use of del

5|Page
delString1

print("\nDeleting entire String: ")

print(String1)

Error:
Traceback (most recent call last):
File "/home/e4b8f2170f140da99d2fe57d9d8c6a94.py", line 12, in
print(String1)
NameError: name 'String1' is not defined
Escape Sequencing in Python
While printing Strings with single and double quotes in it
causes SyntaxError because String already contains Single and Double Quotes
and hence cannot be printed with the use of either of these. Hence, to print such a
String either Triple Quotes are used or Escape sequences are used to print
Strings.
Escape sequences start with a backslash and can be interpreted differently. If
single quotes are used to represent a string, then all the single quotes present in
the string must be escaped and the same is done for Double Quotes.
Example:
 Python3

# Python Program for

# Escape Sequencing

# of String

# Initial String

String1 ='''I'm a "Geek"'''

print("Initial String with use of Triple Quotes: ")

print(String1)

6|Page
# Escaping Single Quote

String1 ='I\'m a "Geek"'

print("\nEscaping Single Quote: ")

print(String1)

# Escaping Double Quotes

String1 ="I'm a \"Geek\""

print("\nEscaping Double Quotes: ")

print(String1)

# Printing Paths with the

# use of Escape Sequences

String1 ="C:\\Python\\Geeks\\"

print("\nEscaping Backslashes: ")

print(String1)

# Printing Paths with the

# use of Tab

String1 ="Hi\tGeeks"

print("\nTab: ")

print(String1)

7|Page
# Printing Paths with the

# use of New Line

String1 ="Python\nGeeks"

print("\nNew Line: ")

print(String1)

Output:
Initial String with use of Triple Quotes:
I'm a "Geek"
Escaping Single Quote:
I'm a "Geek"
Escaping Double Quotes:
I'm a "Geek"
Escaping Backslashes:
C:\Python\Geeks\
Tab:
Hi Geeks
New Line:
Python
Geeks
Formatting of Strings
Strings in Python can be formatted with the use of format() method which is a
very versatile and powerful tool for formatting Strings. Format method in String
contains curly braces {} as placeholders which can hold arguments according to
position or keyword to specify the order.
Example 1:
In this example, we will declare a string which contains the curly braces {} that
acts as a placeholders and provide them values to see how string declaration
position matters.
 Python3

# Python Program for

# Formatting of Strings

8|Page
# Default order

String1 ="{} {} {}".format('Geeks', 'For', 'Life')

print("Print String in default order: ")

print(String1)

# Positional Formatting

String1 ="{1} {0} {2}".format('Geeks', 'For', 'Life')

print("\nPrint String in Positional order: ")

print(String1)

# Keyword Formatting

String1 ="{l} {f} {g}".format(g='Geeks', f='For', l='Life')

print("\nPrint String in order of Keywords: ")

print(String1)

Output:
Print String in default order:
Geeks For Life
Print String in Positional order:
For Geeks Life
Print String in order of Keywords:
Life For Geeks
Example 2:
Integers such as Binary, hexadecimal, etc., and floats can be rounded or displayed
in the exponent form with the use of format specifiers.
 Python3

# Formatting of Integers

9|Page
String1 ="{0:b}".format(16)

print("\nBinary representation of 16 is ")

print(String1)

# Formatting of Floats

String1 ="{0:e}".format(165.6458)

print("\nExponent representation of 165.6458 is ")

print(String1)

# Rounding off Integers

String1 ="{0:.2f}".format(1/6)

print("\none-sixth is : ")

print(String1)

Output:
Binary representation of 16 is
10000
Exponent representation of 165.6458 is
1.656458e+02
one-sixth is :
0.17
Example 3:
A string can be left, right, or center aligned with the use of format specifiers,
separated by a colon(:). The (<) indicates that the string should be aligned to the
left, (>) indicates that the string should be aligned to the right and (^) indicates
that the string should be aligned to the center. We can also specify the length in
which it should be aligned. For example, (<10) means that the string should be
aligned to the left within a field of width of 10 characters.
 Python3

10 | P a g e
# String alignment

String1 ="|{:<10}|{:^10}|{:>10}|".format('Geeks',

'for',

'Geeks')

print("\nLeft, center and right alignment with Formatting: ")

print(String1)

# To demonstrate aligning of spaces

String1 ="\n{0:^16} was founded in {1:<4}!".format("GeeksforGeeks",

2009)

print(String1)

Output:
Left, center and right alignment with Formatting:
|Geeks | for | Geeks|
GeeksforGeeks was founded in 2009 !
Example 4:
Old-style formatting was done without the use of the format method by
using the % operator
 Python3

# Python Program for

# Old Style Formatting

# of Integers

11 | P a g e
Integer1 =12.3456789

print("Formatting in 3.2f format: ")

print('The value of Integer1 is %3.2f'%Integer1)

print("\nFormatting in 3.4f format: ")

print('The value of Integer1 is %3.4f'%Integer1)

Output:
Formatting in 3.2f format:
The value of Integer1 is 12.35
Formatting in 3.4f format:
The value of Integer1 is 12.3457

12 | P a g e

You might also like