Category: Strings

  • 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.

  • Modify Strings

    String modification refers to the process of changing the characters of a string. If we talk about modifying a string in Python, what we are talking about is creating a new string that is a variation of the original one.

    In Python, a string (object of str class) is of immutable type. Here, immutable refers to an object thatcannotbe modified in place once it’s created in memory. Unlike a list, we cannot overwrite any character in the sequence, nor can we insert or append characters to it directly. If we need to modify a string, we will use certain string methods that return anewstring object. However, the original string remains unchanged.

    We can use any of the following tricks as a workaround to modify a string.

    Converting a String to a List

    Both strings and lists in Python are sequence types, they are interconvertible. Thus, we can cast a string to a list, modify the list using methods like insert()append(), or remove() and then convert the list back to a string to obtain a modified version.

    Suppose, we have a string variable s1 with WORD as its value and we are required to convert it into a list. For this operation, we can use the list() built-in function and insert a character L at index 3. Then, we can concatenate all the characters using join() method of str class.

    Example

    The below example practically illustrates how to convert a string into a list.

    s1="WORD"print("original string:", s1)
    l1=list(s1)
    
    l1.insert(3,"L")print(l1)
    
    s1=''.join(l1)print("Modified string:", s1)

    It will produce the following output −

    original string: WORD
    ['W', 'O', 'R', 'L', 'D']
    Modified string: WORLD

    Using the Array Module

    To modify a string, construct an array object using the Python standard library named array module. It will create an array of Unicode type from a string variable.

    Example

    In the below example, we are using array module to modify the specified string.

    import array as ar
    
    # initializing a string
    s1="WORD"print("original string:", s1)# converting it to an array
    sar=ar.array('u', s1)# inserting an element
    sar.insert(3,"L")# getting back the modified string
    s1=sar.tounicode()print("Modified string:", s1)

    It will produce the following output −

    original string: WORD
    Modified string: WORLD
    

    Using the StringIO Class

    Python’s io module defines the classes to handle streams. The StringIO class represents a text stream using an in-memory text buffer. A StringIO object obtained from a string behaves like a File object. Hence we can perform read/write operations on it. The getvalue() method of StringIO class returns a string.

    Example

    Let us use the above discussed principle in the following program to modify a string.

    import io
    
    s1="WORD"print("original string:", s1)
    
    sio=io.StringIO(s1)
    sio.seek(3)
    sio.write("LD")
    s1=sio.getvalue()print("Modified string:", s1)

    It will produce the following output −

    original string: WORD
    Modified string: WORLD
  •  Slicing Strings

    Python String slicing is a way of creating a sub-string from a given string. In this process, we extract a portion or piece of a string. Usually, we use the slice operator “[ : ]” to perform slicing on a Python String. Before proceeding with string slicing let’s understand string indexing.

    In Python, a string is an ordered sequence of Unicode characters. Each character in the string has a unique index in the sequence. The index starts with 0. First character in the string has its positional index 0. The index keeps incrementing towards the end of string.

    If a string variable is declared as var=”HELLO PYTHON”, index of each character in the string is as follows −

    string index representation

    Python String Indexing

    Python allows you to access any individual character from the string by its index. In this case, 0 is the lower bound and 11 is the upper bound of the string. So, var[0] returns H, var[6] returns P. If the index in square brackets exceeds the upper bound, Python raises IndexError.

    Example

    In the below example, we accessing the characters of a string through index.

    var ="HELLO PYTHON"print(var[0])print(var[7])print(var[11])print(var[12])

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

    H
    Y
    N
    ERROR!
    Traceback (most recent call last):
      File "<main.py>", line 5, in <module>
    IndexError: string index out of range

    Python String Negative & Positive Indexing

    One of the unique features of Python sequence types (and therefore a string object) is that it has a negative indexing scheme also. In the example above, a positive indexing scheme is used where the index increments from left to right. In case of negative indexing, the character at the end has -1 index and the index decrements from right to left, as a result the first character H has -12 index.

    positive negative indexing

    Example

    Let us use negative indexing to fetch N, Y, and H characters.

    var ="HELLO PYTHON"print(var[-1])print(var[-5])print(var[-12])

    On executing the above code, it will give the following result −

    N
    Y
    H
    

    We can therefore use positive or negative index to retrieve a character from the string.

    In Python, string is an immutable object. The object is immutable if it cannot be modified in-place, once stored in a certain memory location. You can retrieve any character from the string with the help of its index, but you cannot replace it with another character.

    Example

    In the following example, character Y is at index 7 in HELLO PYTHON. Try to replace Y with y and see what happens.

    var="HELLO PYTHON"
    var[7]="y"print(var)

    It will produce the following output −

    Traceback (most recent call last):
     File "C:\Users\users\example.py", line 2, in <module>
      var[7]="y"
      ~~~^^^
    TypeError: 'str' object does not support item assignment
    

    The TypeError is because the string is immutable.

    Python String Slicing

    Python defines “:” as string slicing operator. It returns a substring from the original string. Its general usage is as follows −

    substr=var[x:y]

    The “:” operator needs two integer operands (both of which may be omitted, as we shall see in subsequent examples). The first operand x is the index of the first character of the desired slice. The second operand y is the index of the character next to the last in the desired string. So var(x:y] separates characters from xth position to (y-1)th position from the original string.

    Example

    var="HELLO PYTHON"print("var:",var)print("var[3:8]:", var[3:8])

    It will produce the following output −

    var: HELLO PYTHON
    var[3:8]: LO PY
    

    Python String Slicing With Negative Indexing

    Like positive indexes, negative indexes can also be used for slicing.

    Example

    The below example shows how to slice a string using negative indexes.

    var="HELLO PYTHON"print("var:",var)print("var[3:8]:", var[3:8])print("var[-9:-4]:", var[-9:-4])

    It will produce the following output −

    var: HELLO PYTHON
    var[3:8]: LO PY
    var[-9:-4]: LO PY
    

    Default Values of Indexes with String Slicing

    Both the operands for Python’s Slice operator are optional. The first operand defaults to zero, which means if we do not give the first operand, the slice starts of character at 0th index, i.e. the first character. It slices the leftmost substring up to “y-1” characters.

    Example

    In this example, we are performing slice operation using default values.

    var="HELLO PYTHON"print("var:",var)print("var[0:5]:", var[0:5])print("var[:5]:", var[:5])

    It will produce the following output −

    var: HELLO PYTHON
    var[0:5]: HELLO
    var[:5]: HELLO
    

    Example

    Similarly, y operand is also optional. By default, it is “-1”, which means the string will be sliced from the xth position up to the end of string.

    var="HELLO PYTHON"print("var:",var)print("var[6:12]:", var[6:12])print("var[6:]:", var[6:])

    It will produce the following output −

    var: HELLO PYTHON
    var[6:12]: PYTHON
    var[6:]: PYTHON
    

    Example

    Naturally, if both the operands are not used, the slice will be equal to the original string. That’s because “x” is 0, and “y” is the last index+1 (or -1) by default.

    var="HELLO PYTHON"print("var:",var)print("var[0:12]:", var[0:12])print("var[:]:", var[:])

    It will produce the following output −

    var: HELLO PYTHON
    var[0:12]: HELLO PYTHON
    var[:]: HELLO PYTHON
    

    Example

    The left operand must be smaller than the operand on right, for getting a substring of the original string. Python doesn’t raise any error, if the left operand is greater, bu returns a null string.

    Open Compiler

    var="HELLO PYTHON"print("var:",var)print("var[-1:7]:", var[-1:7])print("var[7:0]:", var[7:0])

    It will produce the following output −

    var: HELLO PYTHON
    var[-1:7]:
    var[7:0]:
    

    Return Type of String Slicing

    Slicing returns a new string. You can very well perform string operations like concatenation, or slicing on the sliced string.

    Example

    var="HELLO PYTHON"print("var:",var)print("var[:6][:2]:", var[:6][:2])
    
    var1=var[:6]print("slice:", var1)print("var1[:2]:", var1[:2])

    It will produce the following output −

    var: HELLO PYTHON
    var[:6][:2]: HE
    slice: HELLO
    var1[:2]: HE
  •  Strings

    In Python, a string is an immutable sequence of Unicode characters. Each character has a unique numeric value as per the UNICODE standard. But, the sequence as a whole, doesn’t have any numeric value even if all the characters are digits. To differentiate the string from numbers and other identifiers, the sequence of characters is included within single, double or triple quotes in its literal representation. Hence, 1234 is a number (integer) but ‘1234’ is a string.

    Creating Python Strings

    As long as the same sequence of characters is enclosed, single or double or triple quotes don’t matter. Hence, following string representations are equivalent.

    Example

    >>>'Welcome To TutorialsPoint''Welcome To TutorialsPoint'>>>"Welcome To TutorialsPoint"'Welcome To TutorialsPoint'>>>'''Welcome To TutorialsPoint''''Welcome To TutorialsPoint'>>>"""Welcome To TutorialsPoint"""'Welcome To TutorialsPoint'

    Looking at the above statements, it is clear that, internally Python stores strings as included in single quotes.

    In older versions strings are stored internally as 8-bit ASCII, hence it is required to attach ‘u’ to make it Unicode. Since Python 3, all strings are represented in Unicode. Therefore, It is no longer necessary now to add ‘u’ after the string.

    Accessing Values in Strings

    Python does not support a character type; these are treated as strings of length one, thus also considered a substring.

    To access substrings, use the square brackets for slicing along with the index or indices to obtain your substring. For example −

    Open Compiler

    var1 ='Hello World!'
    var2 ="Python Programming"print("var1[0]: ", var1[0])print("var2[1:5]: ", var2[1:5])

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

    var1[0]:  H
    var2[1:5]:  ytho
    

    Updating Strings

    You can “update” an existing string by (re)assigning a variable to another string. The new value can be related to its previous value or to a completely different string altogether. For example −

    Open Compiler

    var1 ='Hello World!'print("Updated String :- ", var1[:6]+'Python')

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

    Updated String :-  Hello Python
    

    Visit our Python – Modify Strings tutorial to know more about updating/modifying strings.

    Escape Characters

    Following table is a list of escape or non-printable characters that can be represented with backslash notation.

    An escape character gets interpreted; in a single quoted as well as double quoted strings.

    Backslash notationHexadecimal characterDescription
    \a0x07Bell or alert
    \b0x08Backspace
    \cxControl-x
    \C-xControl-x
    \e0x1bEscape
    \f0x0cFormfeed
    \M-\C-xMeta-Control-x
    \n0x0aNewline
    \nnnOctal notation, where n is in the range 0.7
    \r0x0dCarriage return
    \s0x20Space
    \t0x09Tab
    \v0x0bVertical tab
    \xCharacter x
    \xnnHexadecimal notation, where n is in the range 0.9, a.f, or A.F

    String Special Operators

    Assume string variable a holds ‘Hello’ and variable b holds ‘Python’, then −

    OperatorDescriptionExample
    &plus;Concatenation – Adds values on either side of the operatora &plus; b will give HelloPython
    *Repetition – Creates new strings, concatenating multiple copies of the same stringa*2 will give -HelloHello
    []Slice – Gives the character from the given indexa[1] will give e
    [ : ]Range Slice – Gives the characters from the given rangea[1:4] will give ell
    inMembership – Returns true if a character exists in the given stringH in a will give 1
    not inMembership – Returns true if a character does not exist in the given stringM not in a will give 1
    r/RRaw String – Suppresses actual meaning of Escape characters. The syntax for raw strings is exactly the same as for normal strings with the exception of the raw string operator, the letter “r,” which precedes the quotation marks. The “r” can be lowercase (r) or uppercase (R) and must be placed immediately preceding the first quote mark.print r’\n’ prints \n and print R’\n’prints \n
    %Format – Performs String formattingSee at next section

    String Formatting Operator

    One of Python’s coolest features is the string format operator %. This operator is unique to strings and makes up for the pack of having functions from C’s printf() family. Following is a simple example −

    Open Compiler

    print("My name is %s and weight is %d kg!"%('Zara',21))

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

    My name is Zara and weight is 21 kg!
    

    Here is the list of complete set of symbols which can be used along with % −

    Sr.No.Format Symbol & Conversion
    1%ccharacter
    2%sstring conversion via str() prior to formatting
    3%isigned decimal integer
    4%dsigned decimal integer
    5%uunsigned decimal integer
    6%ooctal integer
    7%xhexadecimal integer (lowercase letters)
    8%Xhexadecimal integer (UPPERcase letters)
    9%eexponential notation (with lowercase ‘e’)
    10%Eexponential notation (with UPPERcase ‘E’)
    11%ffloating point real number
    12%gthe shorter of %f and %e
    13%Gthe shorter of %f and %E

    Other supported symbols and functionality are listed in the following table −

    Sr.No.Symbol & Functionality
    1*argument specifies width or precision
    2left justification
    3&plus;display the sign
    4<sp>leave a blank space before a positive number
    5#add the octal leading zero ( ‘0’ ) or hexadecimal leading ‘0x’ or ‘0X’, depending on whether ‘x’ or ‘X’ were used.
    60pad from left with zeros (instead of spaces)
    7%‘%%’ leaves you with a single literal ‘%’
    8(var)mapping variable (dictionary arguments)
    9m.n.m is the minimum total width and n is the number of digits to display after the decimal point (if appl.)

    Visit our Python – String Formatting tutorial to learn about various ways to format strings.

    Double Quotes in Python Strings

    You want to embed some text in double quotes as a part of string, the string itself should be put in single quotes. To embed a single quoted text, string should be written in double quotes.

    Example

    var ='Welcome to "Python Tutorial" from TutorialsPoint'print("var:", var)
    
    var ="Welcome to 'Python Tutorial' from TutorialsPoint"print("var:", var)

    It will produce the following output −

    var: Welcome to "Python Tutorial" from TutorialsPoint
    var: Welcome to 'Python Tutorial' from TutorialsPoint
    

    Triple Quotes

    To form a string with triple quotes, you may use triple single quotes, or triple double quotes − both versions are similar.

    Example

    var ='''Welcome to TutorialsPoint'''print("var:", var)
    
    var ="""Welcome to TutorialsPoint"""print("var:", var)

    It will produce the following output −

    var: Welcome to TutorialsPoint
    var: Welcome to TutorialsPoint
    

    Python Multiline Strings

    Triple quoted string is useful to form a multi-line string.

    Example

    var ='''
    Welcome To
    Python Tutorial
    from TutorialsPoint
    '''print("var:", var)

    It will produce the following output −

    var:
    Welcome To
    Python Tutorial
    from TutorialsPoint
    

    Arithmetic Operators with Strings

    A string is a non-numeric data type. Obviously, we cannot use arithmetic operators with string operands. Python raises TypeError in such a case.

    print("Hello"-"World")

    On executing the above program it will generate the following error −

    >>> "Hello"-"World"
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: unsupported operand type(s) for -: 'str' and 'str'
    

    Getting Type of Python Strings

    A string in Python is an object of str class. It can be verified with type() function.

    Example

    var ="Welcome To TutorialsPoint"print(type(var))

    It will produce the following output −

    <class 'str'>
    

    Built-in String Methods

    Python includes the following built-in methods to manipulate strings −

    Sr.No.Methods with 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.
    3center(width, fillchar)Returns a space-padded string with the original string centered to a total of width columns.
    4count(str, beg= 0,end=len(string))Counts how many times str occurs in string or in a substring of string if starting index beg and ending index end are given.
    5decode(encoding=’UTF-8′,errors=’strict’)Decodes the string using the codec registered for encoding. encoding defaults to the default string encoding.
    6encode(encoding=’UTF-8′,errors=’strict’)Returns encoded string version of string; on error, default is to raise a ValueError unless errors is given with ‘ignore’ or ‘replace’.
    7endswith(suffix, beg=0, end=len(string))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.
    8expandtabs(tabsize=8)Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not provided.
    9find(str, beg=0 end=len(string))Determine if str 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.
    10format(*args, **kwargs)This method is used to format the current string value.
    11format_map(mapping)This method is also use to format the current string the only difference is it uses a mapping object.
    12index(str, beg=0, end=len(string))Same as find(), but raises an exception if str not found.
    13isalnum()Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.
    14isalpha()Returns true if string has at least 1 character and all characters are alphabetic and false otherwise.
    15isascii()Returns True is all the characters in the string are from the ASCII character set.
    16isdecimal()Returns true if a unicode string contains only decimal characters and false otherwise.
    17isdigit()Returns true if string contains only digits and false otherwise.
    18isidentifier()Checks whether the string is a valid Python identifier.
    19islower()Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise.
    20isnumeric()Returns true if a unicode string contains only numeric characters and false otherwise.
    21isprintable()Checks whether all the characters in the string are printable.
    22isspace()Returns true if string contains only whitespace characters and false otherwise.
    23istitle()Returns true if string is properly “titlecased” and false otherwise.
    24isupper()Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise.
    25join(seq)Merges (concatenates) the string representations of elements in sequence seq into a string, with separator string.
    26ljust(width[, fillchar])Returns a space-padded string with the original string left-justified to a total of width columns.
    27lower()Converts all uppercase letters in string to lowercase.
    28lstrip()Removes all leading white space in string.
    29maketrans()Returns a translation table to be used in translate function.
    30partition()Splits the string in three string tuple at the first occurrence of separator.
    31removeprefix()Returns a string after removing the prefix string.
    32removesuffix()Returns a string after removing the suffix string.
    33replace(old, new [, max])Replaces all occurrences of old in string with new or at most max occurrences if max given.
    34rfind(str, beg=0,end=len(string))Same as find(), but search backwards in string.
    35rindex( str, beg=0, end=len(string))Same as index(), but search backwards in string.
    36rjust(width,[, fillchar])Returns a space-padded string with the original string right-justified to a total of width columns.
    37rpartition()Splits the string in three string tuple at the ladt occurrence of separator.
    38rsplit()Splits the string from the end and returns a list of substrings.
    39rstrip()Removes all trailing whitespace of string.
    40split(str=””, num=string.count(str))Splits string according to delimiter str (space if not provided) and returns list of substrings; split into at most num substrings if given.
    41splitlines( num=string.count(‘\n’))Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs removed.
    42startswith(str, beg=0,end=len(string))Determines if string or a substring of string (if starting index beg and ending index end are given) starts with substring str; returns true if so and false otherwise.
    43strip([chars])Performs both lstrip() and rstrip() on string.
    44swapcase()Inverts case for all letters in string.
    45title()Returns “titlecased” version of string, that is, all words begin with uppercase and the rest are lowercase.
    46translate(table, deletechars=””)Translates string according to translation table str(256 chars), removing those in the del string.
    47upper()Converts lowercase letters in string to uppercase.
    48zfill (width)Returns original string leftpadded with zeros to a total of width characters; intended for numbers, zfill() retains any sign given (less one zero).

    Built-in Functions with Strings

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

    Sr.No.Function with Description
    1len(list)Returns the length of the string.
    2max(list)Returns the max alphabetical character from the string str.
    3min(list)Returns the min alphabetical character from the string str.