Thursday, 4 April 2024

Python String

 

String


In Python, Strings are arrays 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. Square brackets can be used to access elements of the string.


1. Accessing and Slicing a Tuple

Strings in Python can be created using single quotes or double quotes or even triple quotes.

Program:

# Python Program for 

# Creation of String 


# Creating a String 

# with single Quotes 

String1 = 'Welcome to the Balaji Tech'

print("String with the use of Single Quotes: "

print(String1) 


# Creating a String 

# with double Quotes 

String1 = "I'm a BalajiTech"

print("\nString with the use of Double Quotes: "

print(String1) 


# Creating a String 

# with triple Quotes 

String1 = '''I'm a Balaji and I live in a world of "Technology"'''

print("\nString with the use of Triple Quotes: "

print(String1) 


# Creating String with triple 

# Quotes allows multiple lines 

String1 = '''Balaji 

            Tech'''

print("\nCreating a multiline String: "

print(String1) 


# Scripts Ends 

Output:

String with the use of Single Quotes: 

Welcome to the Balaji Tech


String with the use of Double Quotes: 

I'm a BalajiTech


String with the use of Triple Quotes: 

I'm a Balaji and I live in a world of "Technology"


Creating a multiline String: 

Balaji 

            Tech


2. Accessing characters in Python

In Python, individual characters of a String can be accessed by using the method of Indexing. Indexing allows negative address references to access characters from the back of the String, e.g. -1 refers to the last character, -2 refers to the second last character and so on.

While accessing an index out of the range will cause an IndexError. Only Integers are allowed to be passed as an index, float or other types will cause a TypeError.


B

a

l

a

j

t

e

c

0

1

2

3

4

5

6

7

-8

-7

-6

-5

-4

-3

-2

-1


Program:

# Python Program to Access 

# characters of String 


String1 = "BalajiTech"

print("Initial String: "

print(String1) 


# Printing First character 

print("\nFirst character of String is: "

print(String1[0]) 


# Printing Last character 

print("\nLast character of String is: "

print(String1[-1])

# Scripts Ends 

Output:

Initial String: 

BalajiTech


First character of String is: 

B


Last character of String is: 

h


3. String Slicing

To access a range of characters in the String, method of slicing is used. Slicing in a String is done by using a Slicing operator (colon).

Program:

# Python Program to 

# demonstrate String slicing 


# Creating a String 

String1 = "BalajiTech"

print("Initial String: "

print(String1) 


# Printing 6th to 10th character 

print("\nSlicing characters from 6-10: "

print(String1[6:10]) 


# Printing characters between 

# 3rd and 2nd last character 

print("\nSlicing characters between " +

  "3rd and 2nd last character: "

print(String1[3:-2]) 

# Scripts Ends 

Output:

Initial String: 

BalajiTech


Slicing characters from 4-9: 

Tech


Slicing characters between 3rd and 2nd last character: 

ajiTe


4. Deleting or Updating from a String

In Python, 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 it has been assigned. Only new strings can be reassigned to the same name.

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 String is deleted and is unavailable to be printed.

Program:

# Python Program to Update 

# entire String 


String1 = "Hello, I'm a Balaji"

print("Initial String: "

print(String1) 


# Updating a String 

String1 = "Welcome to the Geek Tech"

print("\nUpdated String: "

print(String1) 


# Deleting a String 

# with the use of del 

del String1  

print("\n String1 was Delete: "

# Scripts Ends 

Output:

Initial String: 

Hello, I'm a Balaji


Updated String: 

Welcome to the Geek Tech


 String1 was Delete: 


5. 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 such 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 same is done for Double Quotes.


Program:

# Escape Sequencing of String 

# Initial String 

String1 = '''I'm a "Balaji"'''

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

print(String1) 


# Escaping Single Quote 

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

print("\nEscaping Single Quote: "

print(String1) 


# Escaping Doule Quotes 

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

print("\nEscaping Double Quotes: "

print(String1) 


# Printing Paths with the 

# use of Escape Sequences 

String1 = "C:\\Python\\BT\\"

print("\nEscaping Backslashes: "

print(String1) 

# Scripts Ends 

Output:

Initial String with use of Triple Quotes: 

I'm a "Balaji"


Escaping Single Quote: 

I'm a "Balaji"


Escaping Double Quotes: 

I'm a "Balaji"


Escaping Backslashes: 

C:\Python\BT\



6. Formatting of Strings

Strings in Python can be formatted with the use of format() method which is very versatile and powerful tool for formatting of Strings. Format method in String contains curly braces {} as placeholders which can hold arguments according to position or keyword to specify the order..

Program:

# Default order 

String1 = "{} {} {}".format('Balaji', 'is', 'Technology'

print("Print String in default order: "

print(String1) 


# Positional Formatting 

String1 = "{1} {0} {2}".format('Balaji', 'is', 'Technology'

print("\nPrint String in Positional order: "

print(String1) 


# Keyword Formatting 

String1 = "{l} {f} {g}".format(g = 'Balaji', f = 'is', l = 'Technology'

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

print(String1) 

# Scripts Ends 

Output:

Print String in default order: 

Balaji is Technology


Print String in Positional order: 

is Balaji Technology


Print String in order of Keywords: 

Technology is Balaji


String constants


Built-In Function

Description

string.ascii_letters

Concatenation of the ascii_lowercase and ascii_uppercase constants.

string.ascii_lowercase

Concatenation of lowercase letters

string.ascii_uppercase

Concatenation of uppercase letters

string.digits

Digit in strings

string.hexdigits

Hexadigit in strings

string.letters

concatenation of the strings lowercase and uppercase

string.lowercase

A string must contain lowercase letters.

string.octdigits

Octadigit in a string

string.punctuation

ASCII characters having punctuation characters.

string.printable

String of characters which are printable

String.endswith()

Returns True if a string ends with the given suffix otherwise returns False

String.startswith()

Returns True if a string starts with the given prefix otherwise returns False

String.isdigit()

Returns “True” if all characters in the string are digits, Otherwise, It returns “False”.

String.isalpha()

Returns “True” if all characters in the string are alphabets, Otherwise, It returns “False”.

string.isdecimal()

Returns true if all characters in a string are decimal.

str.format()

one of the string formatting methods in Python3, which allows multiple substitutions and value formatting.

String.index

Returns the position of the first occurrence of substring in a string

string.uppercase

A string must contain uppercase letters.

string.whitespace

A string containing all characters that are considered whitespace.

string.swapcase()

Method converts all uppercase characters to lowercase and vice versa of the given string, and returns it

replace()

returns a copy of the string where all occurrences of a substring is replaced with another substring.



Deprecated string functions


Built-In Function

Description

string.Isdecimal

Returns true if all characters in a string are decimal

String.Isalnum

Returns true if all the characters in a given string are alphanumeric.

string.Istitle

Returns True if the string is a titlecased string

String.partition

splits the string at the first occurrence of the separator and returns a tuple.

String.Isidentifier

Check whether a string is a valid identifier or not.

String.len

Returns the length of the string.

String.rindex

Returns the highest index of the substring inside the string if substring is found.

String.Max

Returns the highest alphabetical character in a string.

String.min

Returns the minimum alphabetical character in a string.

String.splitlines

Returns a list of lines in the string.

string.capitalize

Return a word with its first character capitalized.

string.expandtabs

Expand tabs in a string replacing them by one or more spaces

string.find

Return the lowest indexin a sub string.

string.rfind

find the highest index.

string.count

Return the number of (non-overlapping) occurrences of substring sub in string

string.lower

Return a copy of s, but with upper case letters converted to lower case.

string.split

Return a list of the words of the string,If the optional second argument sep is absent or None

string.rsplit()

Return a list of the words of the string s, scanning s from the end.

rpartition()

Method splits the given string into three parts

string.splitfields

Return a list of the words of the string when only used with two arguments.

string.join

Concatenate a list or tuple of words with intervening occurrences of sep.


No comments:

Post a Comment

Interactive Report: Introduction to the Internet of Things (IoT) ...

Popular Posts