oursolutionarchitectoursolutionarchitect
  • Python Questions and Answers
  • Python - Programming Examples
  • Python - Quick Guide
  • Python - Useful Resources
  • Python - Discussion
    • Selected Reading
    • Q&A

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

    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'>
    

    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)
    

    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)
    

    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
    

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

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