Python Strings

String is a sequence of character defined using quotes. There are four different type of quotes avaialble in Python for string representation. Since there is no seperate character type in Python, any quotes can be used for any string object.

Example

    >>> a = 'Programink'
    >>> b = "Programink"
    >>> c = '''Programink'''
    >>> d = """Programink"""
    >>> a == b == c == d
    True
                                

Three pair of quotes are generally used for multi-line string or docstring. Consistency in use of quotes is very important in Python.

    >>> a = 'It din't rain today'   # incorrect
    >>> a = "It didn't rain today"  # correct
                                

Properties of Python Strings

String data type in Python has below properties:

  • String has sequential index starting from 0 and -1.
    >>> s = "Hello"
    >>> s[0]
    'H'
    >>> s[-1]
    o
    >>> s[:2]
    'He'
                                
  • String is case-sensitive but not quotes sensitive.
    >>> 'a' == 'A'
    False
    >>> 'a' == "a"
    True
                                
  • String supports concatenation and repitition.
    >>> "a" + "b"
    'ab'
    >>> "ha" * 4
    'hahahaha'
                                
  • String is immutable and this it cannot be changed.
    >>> x = "hello"
    >>> y = x.upper()
    >>> print(x)
    'hello'
    >>> print(y)
    'HELLO'
                                

Python String Attributes

String type object in Python has below built-in attributes:

    capitalize
    casefold
    center
    count
    encode
    endswith
    expandtabs
    find
    format
    format_map
    index
    isalnum
    isalpha
    isascii
    isdecimal
    isdigit
    isidentifier
    islower
    isnumeric
    isprintable
    isspace
    istitle
    isupper
    join
    ljust
    lower
    lstrip
    maketrans
    partition
    replace
    rfind
    rindex
    rjust
    rpartition
    rsplit
    rstrip
    split
    splitlines
    startswith
    strip
    swapcase
    title
    translate
    upper
    zfill