Category: Python Strings

https://learnpython.sweetdishy.com/wp-content/uploads/2026/03/string.png

  • Python – 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
  • Python – 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.
  • Python – 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
  • Python – 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
    • Using format() method of str class
    • Using f-string
    • Using String Template class

    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 ="Learn Python App"print("Welcome to %s!"% name)

    It will produce the following output −

    Welcome to Learn Python App!

    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("Learn Python App"))

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

    Welcome to Learn Python App

    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="Learn Python App")print(new_str)

    It will produce the following output −

    Hello and Welcome to Learn Python App" !
  • Python – 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.

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

    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
  • Python – 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 Learn Python App''Welcome To Learn Python App'>>>"Welcome To TutorialsPoint"'Welcome To Learn Python App'>>>'''Welcome To Learn Python App''''Welcome To Learn Python App'>>>"""Welcome To Learn Python App"""'Welcome To Learn Python App'

    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 −

    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 −

    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 −

    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 Learn Python App("var:", var)

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

    It will produce the following output −

    var: Welcome to "Python Tutorial" from Learn Python App
    var: Welcome to 'Python Tutorial' from Learn Python App

    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 Learn Python App'''print("var:", var)

    var ="""Welcome to Learn Python App"""print("var:", var)

    It will produce the following output −

    var: Welcome to Learn Python App
    var: Welcome to Learn Python App

    Python Multiline Strings

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

    Example

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

    It will produce the following output −

    var:
    Welcome To
    Python Tutorial
    from Learn Python App

    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 Learn Python App"print(type(var))

    It will produce the following output −

    <class 'str'>
  • Python – Strings

    Python has built-in support to store and process numeric data (Python Numbers). Most of the times you work with numbers in almost every Python application. Obviously, any computer application deals with numbers. This tutorial will discuss about different types of Python Numbers and their properties.

    Python – Number Types

    There are three built-in number types available in Python:

    • integers (int)
    • floating point numbers (float)
    • complex numbers

    Python also has a bult-in Boolean data type called bool. It can be treated as a sub-type of int type, since it’s two possible values True and False represent the integers 1 and 0 respectively.

    Python − Integer Numbers

    In Python, any number without the provision to store a fractional part is an integer. (Note that if the fractional part in a number is 0, it doesn’t mean that it is an integer. For example a number 10.0 is not an integer, it is a float with 0 fractional part whose numeric value is 10.) An integer can be zero, positive or a negative whole number. For example, 1234, 0, -55 all represent to integers in Python.

    There are three ways to form an integer object. With (a) literal representation, (b) any expression evaluating to an integer, and (c) using int() function.

    Literal is a notation used to represent a constant directly in the source code. For example −

    >>> a =10

    However, look at the following assignment of the integer variable c.

    a =10
    b =20
    c = a + b
    
    print("a:", a,"type:",type(a))print("c:", c,"type:",type(c))

    It will produce the following output −

    a: 10 type: <class 'int'>
    c: 30 type: <class 'int'>
    

    Here, c is indeed an integer variable, but the expression a + b is evaluated first, and its value is indirectly assigned to c.

    The third method of forming an integer object is with the return value of int() function. It converts a floating point number or a string in an integer.

    >>> a=int(10.5)>>> b=int("100")

    You can represent an integer as a binary, octal or Hexa-decimal number. However, internally the object is stored as an integer.

    Binary Numbers in Python

    A number consisting of only the binary digits (1 and 0) and prefixed with “0b” is a binary number. If you assign a binary number to a variable, it still is an int variable.

    A represent an integer in binary form, store it directly as a literal, or use int() function, in which the base is set to 2

    a=0b101print("a:",a,"type:",type(a))
    
    b=int("0b101011",2)print("b:",b,"type:",type(b))

    It will produce the following output −

    a: 5 type: <class 'int'>
    b: 43 type: <class 'int'>
    

    There is also a bin() function in Python. It returns a binary string equivalent of an integer.

    a=43
    b=bin(a)print("Integer:",a,"Binary equivalent:",b)

    It will produce the following output −

    Integer: 43 Binary equivalent: 0b101011
    

    Octal Numbers in Python

    An octal number is made up of digits 0 to 7 only. In order to specify that the integer uses octal notation, it needs to be prefixed by “0o” (lowercase O) or “0O” (uppercase O). A literal representation of octal number is as follows −

    a=0O107print(a,type(a))

    It will produce the following output −

    71 <class 'int'>
    

    Note that the object is internally stored as integer. Decimal equivalent of octal number 107 is 71.

    Since octal number system has 8 symbols (0 to 7), its base is 7. Hence, while using int() function to covert an octal string to integer, you need to set the base argument to 8.

    a=int('20',8)print(a,type(a))

    It will produce the following output −

    16 <class 'int'>
    

    Decimal equivalent of octal 30 is 16.

    In the following code, two int objects are obtained from octal notations and their addition is performed.

    a=0O56print("a:",a,"type:",type(a))
    
    b=int("0O31",8)print("b:",b,"type:",type(b))
    
    c=a+b
    print("addition:", c)

    It will produce the following output −

    a: 46 type: <class 'int'>
    b: 25 type: <class 'int'>
    addition: 71
    

    To obtain the octal string for an integer, use oct() function.

    a=oct(71)print(a,type(a))

    Hexa-decimal Numbers in Python

    As the name suggests, there are 16 symbols in the Hexadecimal number system. They are 0-9 and A to F. The first 10 digits are same as decimal digits. The alphabets A, B, C, D, E and F are equivalents of 11, 12, 13, 14, 15, and 16 respectively. Upper or lower cases may be used for these letter symbols.

    For the literal representation of an integer in Hexadecimal notation, prefix it by “0x” or “0X”.

    a=0XA2print(a,type(a))

    It will produce the following output −

    162 <class 'int'>
    

    To convert a Hexadecimal string to integer, set the base to 16 in the int() function.

    a=int('0X1e',16)print(a,type(a))

    Try out the following code snippet. It takes a Hexadecimal string, and returns the integer.

    num_string ="A1"
    number =int(num_string,16)print("Hexadecimal:", num_string,"Integer:",number)

    It will produce the following output −

    Hexadecimal: A1 Integer: 161
    

    However, if the string contains any symbol apart from the Hexadecimal symbol chart an error will be generated.

    num_string ="A1X001"print(int(num_string,16))

    The above program generates the following error −

    Traceback (most recent call last):
      File "/home/main.py", line 2, in 
        print (int(num_string, 16))
    ValueError: invalid literal for int() with base 16: 'A1X001'
    

    Python’s standard library has hex() function, with which you can obtain a hexadecimal equivalent of an integer.

    a=hex(161)print(a,type(a))

    It will produce the following output −

    0xa1 <class 'str'>
    

    Though an integer can be represented as binary or octal or hexadecimal, internally it is still integer. So, when performing arithmetic operation, the representation doesn’t matter.

    a=10#decimal
    b=0b10#binary
    c=0O10#octal
    d=0XA#Hexadecimal
    e=a+b+c+d
    
    print("addition:", e)

    It will produce the following output −

    addition: 30
    

    Python − Floating Point Numbers

    A floating point number has an integer part and a fractional part, separated by a decimal point symbol (.). By default, the number is positive, prefix a dash (-) symbol for a negative number.

    A floating point number is an object of Python’s float class. To store a float object, you may use a literal notation, use the value of an arithmetic expression, or use the return value of float() function.

    Using literal is the most direct way. Just assign a number with fractional part to a variable. Each of the following statements declares a float object.

    >>> a=9.99>>> b=0.999>>> c=-9.99>>> d=-0.999

    In Python, there is no restriction on how many digits after the decimal point can a floating point number have. However, to shorten the representation, the E or e symbol is used. E stands for Ten raised to. For example, E4 is 10 raised to 4 (or 4th power of 10), e-3 is 10 raised to -3.

    In scientific notation, number has a coefficient and exponent part. The coefficient should be a float greater than or equal to 1 but less than 10. Hence, 1.23E+3, 9.9E-5, and 1E10 are the examples of floats with scientific notation.

    >>> a=1E10>>> a
    10000000000.0>>> b=9.90E-5>>> b
    9.9e-05>>>1.23E31230.0

    The second approach of forming a float object is indirect, using the result of an expression. Here, the quotient of two floats is assigned to a variable, which refers to a float object.

    a=10.33
    b=2.66
    c=a/b
    
    print("c:", c,"type",type(c))

    It will produce the following output −

    c: 3.8834586466165413 type <class 'float'>
    

    Python’s float() function returns a float object, parsing a number or a string if it has the appropriate contents. If no arguments are given in the parenthesis, it returns 0.0, and for an int argument, fractional part with 0 is added.

    >>> a=float()>>> a
    0.0>>> a=float(10)>>> a
    10.0

    Even if the integer is expressed in binary, octal or hexadecimal, the float() function returns a float with fractional part as 0.

    a=float(0b10)
    b=float(0O10)
    c=float(0xA)print(a,b,c, sep=",")

    It will produce the following output −

    2.0,8.0,10.0
    

    The float() function retrieves a floating point number out of a string that encloses a float, either in standard decimal point format, or having scientific notation.

    a=float("-123.54")
    b=float("1.23E04")print("a=",a,"b=",b)

    It will produce the following output −

    a= -123.54 b= 12300.0
    

    In mathematics, infinity is an abstract concept. Physically, infinitely large number can never be stored in any amount of memory. For most of the computer hardware configurations, however, a very large number with 400th power of 10 is represented by Inf. If you use “Infinity” as argument for float() function, it returns Inf.

    a=1.00E400print(a,type(a))
    a=float("Infinity")print(a,type(a))

    It will produce the following output −

    inf <class 'float'>
    inf <class 'float'>
    

    One more such entity is Nan (stands for Not a Number). It represents any value that is undefined or not representable.

    >>> a=float('Nan')>>> a
    Nan
    

    Python − Complex Numbers

    In this section, we shall know in detail about Complex data type in Python. Complex numbers find their applications in mathematical equations and laws in electromagnetism, electronics, optics, and quantum theory. Fourier transforms use complex numbers. They are Used in calculations with wavefunctions, designing filters, signal integrity in digital electronics, radio astronomy, etc.

    A complex number consists of a real part and an imaginary part, separated by either “+” or “−”. The real part can be any floating point (or itself a complex number) number. The imaginary part is also a float/complex, but multiplied by an imaginary number.

    In mathematics, an imaginary number “i” is defined as the square root of -1 (&bsol;sqrt{−1}). Therefore, a complex number is represented as “x+yi”, where x is the real part, and “y” is the coefficient of imaginary part.

    Quite often, the symbol “j” is used instead of “I” for the imaginary number, to avoid confusion with its usage as current in theory of electricity. Python also uses “j” as the imaginary number. Hence, “x+yj” is the representation of complex number in Python.

    Like int or float data type, a complex object can be formed with literal representation or using complex() function. All the following statements form a complex object.

    >>> a=5+6j>>> a
    (5+6j)>>>type(a)<class'complex'>>>> a=2.25-1.2J>>> a
    (2.25-1.2j)>>>type(a)<class'complex'>>>> a=1.01E-2+2.2e3j>>> a
    (0.0101+2200j)>>>type(a)<class'complex'>

    Note that the real part as well as the coefficient of imaginary part have to be floats, and they may be expressed in standard decimal point notation or scientific notation.

    Python’s complex() function helps in forming an object of complex type. The function receives arguments for real and imaginary part, and returns the complex number.

    There are two versions of complex() function, with two arguments and with one argument. Use of complex() with two arguments is straightforward. It uses first argument as real part and second as coefficient of imaginary part.

    a=complex(5.3,6)
    b=complex(1.01E-2,2.2E3)print("a:", a,"type:",type(a))print("b:", b,"type:",type(b))

    It will produce the following output −

    a: (5.3+6j) type: <class 'complex'>
    b: (0.0101+2200j) type: <class 'complex'>
    

    In the above example, we have used x and y as float parameters. They can even be of complex data type.

    a=complex(1+2j,2-3j)print(a,type(a))

    It will produce the following output −

    (4+4j) <class 'complex'>
    

    Surprised by the above example? Put “x” as 1+2j and “y” as 2-3j. Try to perform manual computation of “x+yj” and you’ll come to know.

    complex(1+2j,2-3j)=(1+2j)+(2-3j)*j
    =1+2j+2j+3=4+4j

    If you use only one numeric argument for complex() function, it treats it as the value of real part; and imaginary part is set to 0.

    a=complex(5.3)print("a:", a,"type:",type(a))

    It will produce the following output −

    a: (5.3+0j) type: <class 'complex'>
    

    The complex() function can also parse a string into a complex number if its only argument is a string having complex number representation.

    In the following snippet, user is asked to input a complex number. It is used as argument. Since Python reads the input as a string, the function extracts the complex object from it.

    a="5.5+2.3j"
    b=complex(a)print("Complex number:", b)

    It will produce the following output −

    Complex number: (5.5+2.3j)
    

    Python’s built-in complex class has two attributes real and imag − they return the real and coefficient of imaginary part from the object.

    a=5+6jprint("Real part:", a.real,"Coefficient of Imaginary part:", a.imag)

    It will produce the following output −

    Real part: 5.0 Coefficient of Imaginary part: 6.0
    

    The complex class also defines a conjugate() method. It returns another complex number with the sign of imaginary component reversed. For example, conjugate of x+yj is x-yj.

    >>> a=5-2.2j>>> a.conjugate()(5+2.2j)

    Number Type Conversion

    Python converts numbers internally in an expression containing mixed types to a common type for evaluation. But sometimes, you need to coerce a number explicitly from one type to another to satisfy the requirements of an operator or function parameter.

    • Type int(x) to convert x to a plain integer.
    • Type long(x) to convert x to a long integer.
    • Type float(x) to convert x to a floating-point number.
    • Type complex(x) to convert x to a complex number with real part x and imaginary part zero. In the same way type complex(x, y) to convert x and y to a complex number with real part x and imaginary part y. x and y are numeric expressions