prev
next
Or press ESC to close.
To continue enjoying our content, please consider disabling your ad blocker. Your support helps us continue providing quality content. To continue enjoying our content, please consider disabling your ad blocker. Your support helps us continue providing quality content.

Python Programming Part 06

Rajjit Sept 22nd, 2023 20 mins read
part-06

TOPIC: Python Strings - Strings Method

Python string
Python string is a sequence of unicode characters that is enclosed in the quotation marks. It is on immutable data type, meaning that once you have created a string, it cannot be changed. Strings are used widely, in mainly different applications such as sorting and manipulating text data, representing names, addresses and other types of data that can be presented as text.
Python does not have a character data type; a single character is simply a string with a length of 1 sequence brackets can be used to access elements of the strings.

Python String Methods:
  • Creating a String in Python:
    string1 = "Welcome All"
    print(string1)
    string2 = "Python strings"
    print(string2)
  • Accessing the characters in Python string:
    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. While accessing an index out of the range will cause an Index error. Only integers are allowed to be passed as an index, float or other types that will cause a Type error.
    string1="Learn Python"
    print("\nFirst Character ", string1[0])
    print("\nLast Character ", string1[-1])
  • Reversing a Python String:
    With accessing characters from a string, it can be reversed by writing [::-1] and the string will be reversed.
    string1 = "Learn Python"
    print(string1[::-1])
    We can also reverse a string by using the built-in "join and reversed" function
    string1 = "Learn Python"
    string2 = "".join(reversed(string1))
    print(string2)
  • String Slicing:
    To access a range of characters in the strings, the method of slicing is used. Slicing in a string is done by using slicing operator(colon).
    string1="Learn Python"
    print("Original string", string1)
    # Printing 3rd to 10th character
    print("\nSlicing character from 3-10")
    print("string1[3:10]")
    # Printing character between 3rd and last 2nd character
    print("\nSlicing character between 3rd and last 2nd character)
    print(string1[3:-2])
  • Deleting and Updating characters in a String:
    In a string, updating or deleting 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 "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 same name.
    # Python Program to update the characters of a string
    string1 = "Learn Python"
    print("Original String: ", string1)
    # updating a character of a string
    list1 = string1[0:2] + 'A' + string1[3:]
    print(list1)
    Updating entire string
    # Python program to update an entire string
    string1 = "Learn Python"
    print("Original String: ", string1)
    # Updating
    string1 = "Welcome to Python World"
    print("\nUpdating string: ", string1)
    Deletion of a character in a String
    # Python Program to delete a character
    string1 = "Learn Python"
    print("Original string: ", string1)
    # Deleting a character 
    string2 = string1[0:2] + string[3:]
    print("\nDeleting character at 2nd index: ", string2)
    Deleting entire string
    Deleting of an entire string is possible with the use of "del" keyword, and if the string is tried to be printed, then error will be produced because sting is deleted and is unavailable to be printed.
    # Python program to delete entire string
    string1 = "Learn Python"
    print("Original string: ", string1)
    # Deleting using del keyword
    del string1
    print(string1)
  • Escape Sequence in Python:
    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. Some examples are:
    # Initial string
    string1 = "We'll learn Python"
    string2 = "We'll learn \'Python\'" # escaping single quote
    string3 = "We'll learn \"Python\"" # escaping double quotes
    string4 = "(:\\Python\\First\\)" # indicates the file path
    string5 = "Hi \tPython" # printing tab
    string6 = "Learn \n Python" # use new line

    Here are some of the most common Escape Sequences that are used in every programming language.
    Sl No. Uses
    \n Represents a newline character.
    \t Represents a tab character.
    \ Represents a backslash character.
    ' Represents a single quotation mark (apostrophe).
    " Represents a double quotation mark.
    \x Represents a character using its hexadecimal ASCII value.

    To ignore the escape sequences in a string, r or R is used, this implies that the string is a raw string and escape sequences inside it are to b ignored.
    # Printing hello in Octal
    string1 = "\110\145\154\154\157"
    string2 = r"\110\145\154\154\157" # using raw string
  • Formatting of a string:
    String 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.
    # Default order
    string1 = "{} {} {}".format("Let's", "Learn", "Python")
    # Positional formatting
    string2 = "{1} {2} {0}".format("Let's", "Learn", "Python")
    Keyword formatting
    string1 = "{l} {L} {P}".format(P = "Python", L = "Learn", l = "let's")
    print(string1)
Video tutorial:

Code as discussed in the video:

# Python Strings and Its Method

myString = "Learning Python from RJ Coding Tips"

# 1. Accessing the characters in Python Strings
# firstChar = myString[0]
# secondChar = myString[1]
# eightChar = myString[8]
# lastChar = myString[-1]
# print(firstChar)
# print(lastChar)
# print(secondChar)
# print(eightChar)

# 2. Reversing a string
# reversedString = myString[::-1]
# reversedString = "".join(reversed(myString))
# print(myString)
# print(reversedString)

# 3. String Slicing - using the colon (:)
# strRange = myString[20:30]
# strRange = myString[20:-1]
# print(strRange)

# 4. updating a string
# print(myString)
# myString = "Learning python is fun"
# print(myString)
# updatedString = myString[0:2] + 'A' + myString[3:]
# print(updatedString)

# 5. Deleting a string
# deletedString = myString[0:5] + myString[7:]
# print(deletedString)
# del myString
# print(myString)

# 6. Escape Sequence

# newString = "We'll learn \t \"python\""
# print(newString)

# 7. formatting a string
string1 = "{} {} {}".format("Learn", "Python", "Programming")
string2 = "{2} {0} {1}".format("Learn", "Python", "Programming")
string3 = "{L} {P} {p2}".format(P="Programming", L="Learn", p2="Python")
print(string3)

You can copy and run this code