Author: Saim Khalid

  •  Remove List Items

    Removing List Items

    Removing list items in Python implies deleting elements from an existing list. Lists are ordered collections of items, and sometimes you need to remove certain elements from them based on specific criteria or indices. When we remove list items, we are reducing the size of the list or eliminating specific elements.

    We can remove list items in Python using various methods such as remove()pop() and clear(). Additionally, we can use the del statement to remove items at a specific index. Let us explore through all these methods in this tutorial.

    Remove List Item Using remove() Method

    The remove() method in Python is used to remove the first occurrence of a specified item from a list.

    We can remove list items using the remove() method by specifying the value we want to remove within the parentheses, like my_list.remove(value), which deletes the first occurrence of value from my_list.

    Example

    In the following example, we are deleting the element “Physics” from the list “list1” using the remove() method −

    list1 =["Rohan","Physics",21,69.75]print("Original list: ", list1)
    
    list1.remove("Physics")print("List after removing: ", list1)

    It will produce the following output −

    Original list: ['Rohan', 'Physics', 21, 69.75]
    List after removing: ['Rohan', 21, 69.75]
    

    Remove List Item Using pop() Method

    The pop() method in Python is used to removes and returns the last element from a list if no index is specified, or removes and returns the element at a specified index, altering the original list.

    We can remove list items using the pop() method by calling it without any arguments my_list.pop(), which removes and returns the last item from my_list, or by providing the index of the item we want to remove my_list.pop(index), which removes and returns the item at that index.

    Example

    The following example shows how you can use the pop() method to remove list items −

    list2 =[25.50,True,-55,1+2j]print("Original list: ", list2)
    list2.pop(2)print("List after popping: ", list2)

    We get the output as shown below −

    Original list: [25.5, True, -55, (1+2j)]
    List after popping: [25.5, True, (1+2j)]
    

    Remove List Item Using clear() Method

    The clear() method in Python is used to remove all elements from a list, leaving it empty.

    We can remove all list items using the clear() method by calling it on the list object like my_list.clear(), which empties my_list, leaving it with no elements.

    Example

    In this example, we are using the clear() method to remove all elements from the list “my_list” −

    my_list =[1,2,3,4,5]# Clearing the list
    my_list.clear()print("Cleared list:", my_list)

    Output of the above code is as follows −

    Cleared list: []
    

    Remove List Item Using del Keyword

    The del keyword in Python is used to delete element either at a specific index or a slice of indices from memory.

    We can remove list items using the del keyword by specifying the index or slice of the items we want to delete, like del my_list[index] to delete a single item or del my_list[start:stop] to delete a range of items.

    Example

    In the below example, we are using the “del” keyword to delete an element at the index “2” from the list “list1” −

    list1 =["a","b","c","d"]print("Original list: ", list1)del list1[2]print("List after deleting: ", list1)

    The result produced is as follows −

    Original list: ['a', 'b', 'c', 'd']
    List after deleting: ['a', 'b', 'd']
    

    Example

    In here, we are deleting a series of consecutive items from a list with the slicing operator −

    list2 =[25.50,True,-55,1+2j]print("List before deleting: ", list2)del list2[0:2]print("List after deleting: ", list2)

    It will produce the following output −

    List before deleting: [25.5, True, -55, (1+2j)]
    List after deleting: [-55, (1+2j)]
  • Add List Items

    Add List Items

    Adding list items in Python implies inserting new elements into an existing list. Lists are mutable, meaning they can be modified after creation, allowing for the addition, removal, or modification of their elements.

    Adding items in a list typically refers to appending new elements to the end of the list, inserting them at specific positions within the list, or extending the list with elements from another iterable object.

    We can add list items in Python using various methods such as append(), extend() and insert(). Let us explore through all these methods in this tutorial.

    Adding List Items Using append() Method

    The append() method in Python is used to add a single element to the end of a list.

    We can add list items using the append() method by specifying the element we want to add within the parentheses, like my_list.append(new_item), which adds new_item to the end of my_list.

    Example

    In the following example, we are adding an element “e” to the end of the list “list1” using the append() method −

    list1 =["a","b","c","d"]print("Original list: ", list1)
    list1.append('e')print("List after appending: ", list1)

    Output

    Following is the output of the above code −

    Original list: ['a', 'b', 'c', 'd']
    List after appending: ['a', 'b', 'c', 'd', 'e']
    

    Adding List Items Using insert() Method

    The insert() method in Python is used to add an element at a specified index (position) within a list, shifting existing elements to accommodate the new one.

    We can add list items using the insert() method by specifying the index position where we want to insert the new item and the item itself within the parentheses, like my_list.insert(index, new_item).

    Example

    In this example, we have an original list containing various items. We use the insert() method to add new elements to the list at specific positions −

    list1 =["Rohan","Physics",21,69.75]
    
    list1.insert(2,'Chemistry')print("List after appending: ", list1)
    
    list1.insert(-1,'Pass')print("List after appending: ", list1)

    After appending ‘Chemistry’ to the list, we get the following output −

    List after appending: ['Rohan', 'Physics', 'Chemistry', 21, 69.75]
    

    Then, by inserting ‘Pass’ at the index “-1”, which originally referred to 69.75, we get −

    List after appending: ['Rohan', 'Physics', 'Chemistry', 21, 'Pass', 69.75]
    

    We can see that “Pass” is not inserted at the updated index “-1”, but the previous index “-1”. This behavior is because when appending or inserting items into a list, Python does not dynamically update negative index positions.

    Adding List Items Using extend() Method

    The extend() method in Python is used to add multiple elements from an iterable (such as another list) to the end of a list.

    We can add list items using the extend() method by passing another iterable containing the elements we want to add, like my_list.extend(iterable), which appends each element from the iterable to the end of my_list.

    Example

    In the below example, we are using the extend() method to add the elements from “another_list” to the end of “list1” −

    # Original list
    list1 =[1,2,3]# Another list to extend with
    another_list =[4,5,6]
    
    list1.extend(another_list)print("Extended list:", list1)

    Output

    Output of the above code is as follows −

    Extended list: [1, 2, 3, 4, 5, 6]
  •  Change List Items

    Change List Items

    List is a mutable data type in Python. It means, the contents of list can be modified in place, after the object is stored in the memory. You can assign a new value at a given index position in the list

    Syntax

    list1[i] = newvalue
    

    Example

    In the following code, we change the value at index 2 of the given list.

    list3 =[1,2,3,4,5]print("Original list ", list3)
    list3[2]=10print("List after changing value at index 2: ", list3)

    It will produce the following output −

    Original list [1, 2, 3, 4, 5]
    List after changing value at index 2: [1, 2, 10, 4, 5]

    Change Consecutive List Items

    You can replace more consecutive items in a list with another sublist.

    Example

    In the following code, items at index 1 and 2 are replaced by items in another sublist.

    list1 =["a","b","c","d"]print("Original list: ", list1)
    
    list2 =['Y','Z']
    list1[1:3]= list2
    
    print("List after changing with sublist: ", list1)

    It will produce the following output −

    Original list: ['a', 'b', 'c', 'd']
    List after changing with sublist: ['a', 'Y', 'Z', 'd']
    

    Change a Range of List Items

    If the source sublist has more items than the slice to be replaced, the extra items in the source will be inserted. Take a look at the following code −

    Example

    list1 =["a","b","c","d"]print("Original list: ", list1)
    list2 =['X','Y','Z']
    list1[1:3]= list2
    print("List after changing with sublist: ", list1)

    It will produce the following output −

    Original list: ['a', 'b', 'c', 'd']
    List after changing with sublist: ['a', 'X', 'Y', 'Z', 'd']
    

    Example

    If the sublist with which a slice of original list is to be replaced, has lesser items, the items with match will be replaced and rest of the items in original list will be removed.

    In the following code, we try to replace “b” and “c” with “Z” (one less item than items to be replaced). It results in Z replacing b and c removed.

    list1 =["a","b","c","d"]print("Original list: ", list1)
    list2 =['Z']
    list1[1:3]= list2
    print("List after changing with sublist: ", list1)

    It will produce the following output −

    Original list: ['a', 'b', 'c', 'd']
    List after changing with sublist: ['a', 'Z', 'd']
    
  • Access List Items

    Access List Items

    In Python, a list is a sequence of elements or objects, i.e. an ordered collection of objects. Similar to arrays, each element in a list corresponds to an index.

    To access the values within a list, we need to use the square brackets “[]” notation and, specify the index of the elements we want to retrieve.

    The index starts from 0 for the first element and increments by one for each subsequent element. Index of the last item in the list is always “length-1”, where “length” represents the total number of items in the list.

    In addition to this, Python provides various other ways to access list items such as slicing, negative indexing, extracting a sublist from a list etc. Let us go through this one-by-one −

    Accessing List Items with Indexing

    As discussed above to access the items in a list using indexing, just specify the index of the element with in the square brackets (“[]”) as shown below −

    mylist[4]

    Example

    Following is the basic example to access list items −

    list1 =["Rohan","Physics",21,69.75]
    list2 =[1,2,3,4,5]print("Item at 0th index in list1: ", list1[0])print("Item at index 2 in list2: ", list2[2])

    It will produce the following output −

    Item at 0th index in list1: Rohan
    Item at index 2 in list2: 3
    

    Access List Items with Negative Indexing

    Negative indexing in Python is used to access elements from the end of a list, with -1 referring to the last element, -2 to the second last, and so on.

    We can also access list items with negative indexing by using negative integers to represent positions from the end of the list.

    Example

    In the following example, we are accessing list items with negative indexing −

    list1 =["a","b","c","d"]
    list2 =[25.50,True,-55,1+2j]print("Item at 0th index in list1: ", list1[-1])print("Item at index 2 in list2: ", list2[-3])

    We get the output as shown below −

    Item at 0th index in list1: d
    Item at index 2 in list2: True
    

    Access List Items with Slice Operator

    The slice operator in Python is used to fetch one or more items from the list. We can access list items with the slice operator by specifying the range of indices we want to extract. It uses the following syntax −

    [start:stop]

    Where,

    • start is the starting index (inclusive).
    • stop is the ending index (exclusive).

    If we does not provide any indices, the slice operator defaults to starting from index 0 and stopping at the last item in the list.

    Example

    In the following example, we are retrieving sublist from index 1 to last in “list1” and index 0 to 1 in “list2”, and retrieving all elements in “list3” −

    list1 =["a","b","c","d"]
    list2 =[25.50,True,-55,1+2j]
    list3 =["Rohan","Physics",21,69.75]print("Items from index 1 to last in list1: ", list1[1:])print("Items from index 0 to 1 in list2: ", list2[:2])print("Items from index 0 to index last in list3", list3[:])

    Following is the output of the above code −

    Items from index 1 to last in list1:  ['b', 'c', 'd']
    Items from index 0 to 1 in list2:  [25.5, True]
    Items from index 0 to index last in list3 ['Rohan', 'Physics', 21, 69.75]
    

    Access Sub List from a List

    A sublist is a part of a list that consists of a consecutive sequence of elements from the original list. We can access a sublist from a list by using the slice operator with appropriate start and stop indices.

    Example

    In this example, we are fetching sublist from index “1 to 2” in “list1” and index “0 to 1” in “list2” using slice operator −

    list1 =["a","b","c","d"]
    list2 =[25.50,True,-55,1+2j]print("Items from index 1 to 2 in list1: ", list1[1:3])print("Items from index 0 to 1 in list2: ", list2[0:2])

    The output obtained is as follows −

    Items from index 1 to 2 in list1: ['b', 'c']
    Items from index 0 to 1 in list2: [25.5, True]
    
  • Lists

    Python Lists

    List is one of the built-in data types in Python. A Python list is a sequence of comma separated items, enclosed in square brackets [ ]. The items in a Python list need not be of the same data type.

    Following are some examples of Python lists −

    list1 =["Rohan","Physics",21,69.75]
    list2 =[1,2,3,4,5]
    list3 =["a","b","c","d"]
    list4 =[25.50,True,-55,1+2j]

    List is an ordered collection of items. Each item in a list has a unique position index, starting from 0.

    A list in Python is similar to an array in C, C++ or Java. However, the major difference is that in C/C++/Java, the array elements must be of same type. On the other hand, Python lists may have objects of different data types.

    A Python list is mutable. Any item from the list can be accessed using its index, and can be modified. One or more objects from the list can be removed or added. A list may have same item at more than one index positions.

    Accessing Values in Lists

    To access values in lists, use the square brackets for slicing along with the index or indices to obtain value available at that index. For example −

    list1 =['physics','chemistry',1997,2000];
    list2 =[1,2,3,4,5,6,7];print("list1[0]: ", list1[0])print("list2[1:5]: ", list2[1:5])

    When the above code is executed, it produces the following result −

    list1[0]:  physics
    list2[1:5]:  [2, 3, 4, 5]
    

    Updating Lists

    You can update single or multiple elements of lists by giving the slice on the left-hand side of the assignment operator, and you can add to elements in a list with the append() method. For example −

    list=['physics','chemistry',1997,2000];print("Value available at index 2 : ")print(list[2])list[2]=2001;print("New value available at index 2 : ")print(list[2])

    When the above code is executed, it produces the following result −

    Value available at index 2 :
    1997
    New value available at index 2 :
    2001
    

    Delete List Elements

    To remove a list element, you can use either the del statement if you know exactly which element(s) you are deleting or the remove() method if you do not know. For example −

    list1 =['physics','chemistry',1997,2000];print(list1)del list1[2];print("After deleting value at index 2 : ")print(list1)

    When the above code is executed, it produces following result −

    ['physics', 'chemistry', 1997, 2000]
    After deleting value at index 2 :
    ['physics', 'chemistry', 2000]
    

    Note − remove() method is discussed in subsequent section.

    Python List Operations

    In Python, List is a sequence. Hence, we can concatenate two lists with “+” operator and concatenate multiple copies of a list with “*” operator. The membership operators “in” and “not in” work with list object.

    Python ExpressionResultsDescription
    [1, 2, 3] + [4, 5, 6][1, 2, 3, 4, 5, 6]Concatenation
    [‘Hi!’] * 4[‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’]Repetition
    3 in [1, 2, 3]TrueMembership

    Indexing, Slicing, and Matrixes

    Because lists are sequences, indexing and slicing work the same way for lists as they do for strings.

    Assuming following input −

    L = ['spam', 'Spam', 'SPAM!']
    
    Python ExpressionResultsDescription
    L[2]SPAM!Offsets start at zero
    L[-2]SpamNegative: count from the right
    L[1:][‘Spam’, ‘SPAM!’]Slicing fetches sections

    Python List Methods

    Python includes following list methods −

    Sr.No.Methods with Description
    1list.append(obj)Appends object obj to list.
    2list.clear()Clears the contents of list.
    3list.copy()Returns a copy of the list object.
    4list.count(obj)Returns count of how many times obj occurs in list
    5list.extend(seq)Appends the contents of seq to list
    6list.index(obj)Returns the lowest index in list that obj appears
    7list.insert(index, obj)Inserts object obj into list at offset index
    8list.pop(obj=list[-1])Removes and returns last object or obj from list
    9list.remove(obj)Removes object obj from list
    10list.reverse()Reverses objects of list in place
    11list.sort([func])Sorts objects of list, use compare func if given

    Built-in Functions with Lists

    Following are the built-in functions we can use with lists −

    Sr.No.Function with Description
    1cmp(list1, list2)Compares elements of both lists.
    2len(list)Gives the total length of the list.
    3max(list)Returns item from the list with max value.
    4min(list)Returns item from the list with min value.
    5list(seq)Converts a tuple into list.
  • String Exercises


    Example 1

    Python program to find number of vowels in a given string.

    mystr ="All animals are equal. Some are more equal"
    vowels ="aeiou"
    count=0for x in mystr:if x.lower()in vowels: count+=1print("Number of Vowels:", count)

    It will produce the following output −

    Number of Vowels: 18
    

    Example 2

    Python program to convert a string with binary digits to integer.

    mystr ='10101'defstrtoint(mystr):for x in mystr:if x notin'01':return"Error. String with non-binary characters"
       num =int(mystr,2)return num
    print("binary:{} integer: {}".format(mystr,strtoint(mystr)))

    It will produce the following output −

    binary:10101 integer: 21
    

    Change mystr to ’10, 101′

    binary:10,101 integer: Error. String with non-binary characters
    

    Example 3

    Python program to drop all digits from a string.

    digits =[str(x)for x inrange(10)]
    mystr ='He12llo, Py00th55on!'
    chars =[]for x in mystr:if x notin digits:
    
      chars.append(x)
    newstr =''.join(chars)print(newstr)

    It will produce the following output −

    Hello, Python!
    

    Exercise Programs

    • Python program to sort the characters in a string
    • Python program to remove duplicate characters from a string
    • Python program to list unique characters with their count in a string
    • Python program to find number of words in a string
    • Python program to remove all non-alphabetic characters from a string
  •  String Methods

    Python’s built-in str class defines different methods. They help in manipulating strings. Since string is an immutable object, these methods return a copy of the original string, performing the respective processing on it. The string methods can be classified in following categories −

    Case Conversion Methods

    This category of built-in methods of Python’s str class deal with the conversion of alphabet characters in the string object. Following methods fall in this category −

    Sr.No.Method & Description
    1capitalize()Capitalizes first letter of string
    2casefold()Converts all uppercase letters in string to lowercase. Similar to lower(), but works on UNICODE characters alos
    3lower()Converts all uppercase letters in string to lowercase.
    4swapcase()Inverts case for all letters in string.
    5title()Returns “titlecased” version of string, that is, all words begin with uppercase and the rest are lowercase.
    6upper()Converts lowercase letters in string to uppercase.

    Alignment Methods

    Following methods in the str class control the alignment of characters within the string object.

    Sr.No.Methods & Description
    1center(width, fillchar)Returns a string padded with fillchar with the original string centered to a total of width columns.
    2ljust(width[, fillchar])Returns a space-padded string with the original string left-justified to a total of width columns.
    3rjust(width,[, fillchar])Returns a space-padded string with the original string right-justified to a total of width columns.
    4expandtabs(tabsize = 8)Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not provided.
    5zfill (width)Returns original string leftpadded with zeros to a total of width characters; intended for numbers, zfill() retains any sign given (less one zero).

    Split and Join Methods

    Python has the following methods to perform split and join operations −

    Sr.No.Method & Description
    1lstrip()Removes all leading whitespace in string.
    2rstrip()Removes all trailing whitespace of string.
    3strip()Performs both lstrip() and rstrip() on string
    4rsplit()Splits the string from the end and returns a list of substrings
    5split()Splits string according to delimiter (space if not provided) and returns list of substrings.
    6splitlines()Splits string at NEWLINEs and returns a list of each line with NEWLINEs removed.
    7partition()Splits the string in three string tuple at the first occurrence of separator
    8rpartition()Splits the string in three string tuple at the ladt occurrence of separator
    9join()Concatenates the string representations of elements in sequence into a string, with separator string.
    10removeprefix()Returns a string after removing the prefix string
    11removesuffix()Returns a string after removing the suffix string

    Boolean String Methods

    Following methods in str class return True or False.

    Sr.No.Methods & Description
    1isalnum()Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.
    2isalpha()Returns true if string has at least 1 character and all characters are alphabetic and false otherwise.
    3isdigit()Returns true if the string contains only digits and false otherwise.
    4islower()Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise.
    5isnumeric()Returns true if a unicode string contains only numeric characters and false otherwise.
    6isspace()Returns true if string contains only whitespace characters and false otherwise.
    7istitle()Returns true if string is properly “titlecased” and false otherwise.
    8isupper()Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise.
    9isascii()Returns True is all the characters in the string are from the ASCII character set
    10isdecimal()Checks if all the characters are decimal characters
    11isidentifier()Checks whether the string is a valid Python identifier
    12isprintable()Checks whether all the characters in the string are printable

    Find and Replace Methods

    Following are the Find and Replace methods in Python −

    Sr.No.Method & Description
    1count(sub, beg ,end)Counts how many times sub occurs in string or in a substring of string if starting index beg and ending index end are given.
    2find(sub, beg, end)Determine if sub occurs in string or in a substring of string if starting index beg and ending index end are given returns index if found and -1 otherwise.
    3index(sub, beg, end)Same as find(), but raises an exception if str not found.
    4replace(old, new [, max])Replaces all occurrences of old in string with new or at most max occurrences if max given.
    5rfind(sub, beg, end)Same as find(), but search backwards in string.
    6rindex( sub, beg, end)Same as index(), but search backwards in string.
    7startswith(sub, beg, end)Determines if string or a substring of string (if starting index beg and ending index end are given) starts with substring sub; returns true if so and false otherwise.
    8endswith(suffix, beg, end)Determines if string or a substring of string (if starting index beg and ending index end are given) ends with suffix; returns true if so and false otherwise.

    Translation Methods

    Following are the Translation methods of the string −

    Sr.No.Method & Description
    1maketrans()Returns a translation table to be used in translate function.
    2translate(table, deletechars=””)Translates string according to translation table str(256 chars), removing those in the del string.
  •  Escape Characters

    Escape Character

    An escape character is a character followed by a backslash (\). It tells the Interpreter that this escape character (sequence) has a special meaning. For instance, \n is an escape sequence that represents a newline. When Python encounters this sequence in a string, it understands that it needs to start a new line.

    Unless an ‘r’ or ‘R’ prefix is present, escape sequences in string and bytes literals are interpreted according to rules similar to those used by Standard C. In Python, a string becomes a raw string if it is prefixed with “r” or “R” before the quotation symbols. Hence ‘Hello’ is a normal string whereas r’Hello’ is a raw string.

    Example

    In the below example, we are practically demonstrating raw and normal string.

    # normal string
    normal ="Hello"print(normal)# raw string
    raw =r"Hello"print(raw)

    Output of the above code is shown below −

    Hello
    Hello
    

    In normal circumstances, there is no difference between the two. However, when the escape character is embedded in the string, the normal string actually interprets the escape sequence, whereas the raw string doesn’t process the escape character.

    Example

    In the following example, when a normal string is printed the escape character ‘\n’ is processed to introduce a newline. However, because of the raw string operator ‘r’ the effect of escape character is not translated as per its meaning.

    normal ="Hello\nWorld"print(normal)
    
    raw =r"Hello\nWorld"print(raw)

    On running the above code, it will print the following result −

    Hello
    World
    Hello\nWorld

    Escape Characters in Python

    The following table shows the different escape characters used in Python –

    Sr.NoEscape Sequence & Meaning
    1\<newline>Backslash and newline ignored
    2\\Backslash (\)
    3\’Single quote (‘)
    4\”Double quote (“)
    5\aASCII Bell (BEL)
    6\bASCII Backspace (BS)
    7\fASCII Formfeed (FF)
    8\nASCII Linefeed (LF)
    9\rASCII Carriage Return (CR)
    10\tASCII Horizontal Tab (TAB)
    11\vASCII Vertical Tab (VT)
    12\oooCharacter with octal value ooo
    13\xhhCharacter with hex value hh

    Escape Characters Example

    The following code shows the usage of escape sequences listed in the above table −

    # ignore \
    s = 'This string will not include \
    backslashes or newline characters.'
    print(s)# escape backslash
    s=s ='The \\character is called backslash'print(s)# escape single quote
    s='Hello \'Python\''print(s)# escape double quote
    s="Hello \"Python\""print(s)# escape \b to generate ASCII backspace
    s='Hel\blo'print(s)# ASCII Bell character
    s='Hello\a'print(s)# newline
    s='Hello\nPython'print(s)# Horizontal tab
    s='Hello\tPython'print(s)# form feed
    s="hello\fworld"print(s)# Octal notation
    s="\101"print(s)# Hexadecimal notation
    s="\x41"print(s)

    It will produce the following output −

    This string will not include backslashes or newline characters.
    The \character is called backslash
    Hello 'Python'
    Hello "Python"
    Helo
    Hello
    Hello
    Python
    Hello Python
    hello
    world
    A
    A
  • String Formatting

    String formatting in Python is the process of building a string representation dynamically by inserting the value of numeric expressions in an already existing string. Python’s string concatenation operator doesn’t accept a non-string operand. Hence, Python offers following string formatting techniques −

    Using % operator

    The “%” (modulo) operator often referred to as the string formatting operator. It takes a format string along with a set of variables and combine them to create a string that contain values of the variables formatted in the specified way.

    Example

    To insert a string into a format string using the “%” operator, we use “%s” as shown in the below example −

    name ="Tutorialspoint"print("Welcome to %s!"% name)

    It will produce the following output −

    Welcome to Tutorialspoint!

    Using format() method

    It is a built-in method of str class. The format() method works by defining placeholders within a string using curly braces “{}”. These placeholders are then replaced by the values specified in the method’s arguments.

    Example

    In the below example, we are using format() method to insert values into a string dynamically.

    str="Welcome to {}"print(str.format("Tutorialspoint"))

    On running the above code, it will produce the following output −

    Welcome to Tutorialspoint
    

    Using f-string

    The f-strings, also known as formatted string literals, is used to embed expressions inside string literals. The “f” in f-strings stands for formatted and prefixing it with strings creates an f-string. The curly braces “{}” within the string will then act as placeholders that is filled with variables, expressions, or function calls.

    Example

    The following example illustrates the working of f-strings with expressions.

    item1_price =2500
    item2_price =300
    total =f'Total: {item1_price + item2_price}'print(total)

    The output of the above code is as follows −

    Total: 2800
    

    Using String Template class

    The String Template class belongs to the string module and provides a way to format strings by using placeholders. Here, placeholders are defined by a dollar sign ($) followed by an identifier.

    Example

    The following example shows how to use Template class to format strings.

    from string import Template
    
    # Defining template stringstr="Hello and Welcome to $name !"# Creating Template object
    templateObj = Template(str)# now provide values
    new_str = templateObj.substitute(name="Tutorialspoint")print(new_str)

    It will produce the following output −

    Hello and Welcome to Tutorialspoint !
  • String Concatenation

    Concatenate Strings in Python

    String concatenation in Python is the operation of joining two or more strings together. The result of this operation will be a new string that contains the original strings. The diagram below shows a general string concatenation operation −

    String Concatenation

    In Python, there are numerous ways to concatenate strings. We are going to discuss the following −

    • Using ‘+’ operator
    • Concatenating String with space
    • Using multiplication operator
    • Using ‘+’ and ‘*’ operators together

    String Concatenation using ‘+’ operator

    The “+” operator is well-known as an addition operator, returning the sum of two numbers. However, the “+” symbol acts as string concatenation operator in Python. It works with two string operands, and results in the concatenation of the two.

    The characters of the string on the right of plus symbol are appended to the string on its left. Result of concatenation is a new string.

    Example

    The following example shows string concatenation operation in Python using + operator.

    str1="Hello"
    str2="World"print("String 1:",str1)print("String 2:",str2)
    str3=str1+str2
    print("String 3:",str3)

    It will produce the following output −

    String 1: Hello
    String 2: World
    String 3: HelloWorld
    

    Concatenating String with space

    To insert a whitespace between two strings, we can use a third empty string.

    Example

    In the below example, we are inserting space between two strings while concatenation.

    str1="Hello"
    str2="World"
    blank=" "print("String 1:",str1)print("String 2:",str2)
    str3=str1+blank+str2
    print("String 3:",str3)

    It will produce the following output −

    String 1: Hello
    String 2: World
    String 3: Hello World
    

    String Concatenation By Multiplying

    Another symbol *, which we normally use for multiplication of two numbers, can also be used with string operands. Here, * acts as a repetition operator in Python. One of the operands must be an integer, and the second a string. The integer operand specifies the number of copies of the string operand to be concatenated.

    Example

    In this example, the * operator concatenates multiple copies of the string.

    newString ="Hello"*3print(newString)

    The above code will produce the following output −

    HelloHelloHello
    

    String Concatenation With ‘+’ and ‘*’ Operators

    Both the repetition operator (*) and the concatenation operator (+), can be used in a single expression to concatenate strings. The “*” operator has a higher precedence over the “+” operator.

    Example

    In the below example, we are concatenating strings using the + and * operator together.

    str1="Hello"
    str2="World"print("String 1:",str1)print("String 2:",str2)
    str3=str1+str2*3print("String 3:",str3)
    str4=(str1+str2)*3print("String 4:", str4)

    To form str3 string, Python concatenates 3 copies of World first, and then appends the result to Hello

    String 3: HelloWorldWorldWorld
    

    In the second case, the strings str1 and str2 are inside parentheses, hence their concatenation takes place first. Its result is then replicated three times.

    String 4: HelloWorldHelloWorldHelloWorld
    

    Apart from + and *, no other arithmetic operators can be used with string operands.