String

  • Tutorial

Python String:

Strings are sequences of characters. Your name can be considered a string. Or, say you live in Zambia, then your country name is "Zambia", which is a string.

In this tutorial you will see how strings are treated in Python, the different ways in which strings are represented in Python, and the ways in which you can use strings in your code.

How to create a string and assign it to a variable

To create a string, put the sequence of characters inside either single quotes, double quotes, or triple quotes and then assign it to a variable. You can look into how variables work in Python in the Python variables tutorial.

For example, you can assign a character ‘a’ to a variable single_quote_character. Note that the string is a single character and it is “enclosed” by single quotes.

>>> single_quote_character = 'a'
>>> print(single_quote_character)
a
>>> print(type(single_quote_character)) # check the type of the variable.
<class 'str'>

Similarly, you can assign a single character to a variable double_quote_character. Note that the string is a single character but it is “enclosed” by double quotes.

>>> double_quote_character = "b"
>>> print(double_quote_character)
b
>>> print(type(double_quote_character))
<class 'str'>

Also check out if you can assign a sequence of characters or multiple characters to a variable. You can assign both single quote sequences and double quote sequences.

>>> double_quote_multiple_characters = "aeiou"
>>> single_quote_multiple_characters = 'aeiou'
>>> print(type(double_quote_multiple_characters), type(single_quote_multiple_characters))
<class 'str'> <class 'str'>

Interestingly if you check the equivalence of one to the other using the keyword is, it returns True.

>>> print(double_quote_multiple_characters is double_quote_multiple_characters)
True

Take a look at assignment of strings using triple quotes and check if they belong to the class str as well.

>>> triple_quote_example = """this is a sentence written in triple quotes"""
>>> print(type(triple_quote_example))
<class 'str'>

In the examples above, the function type is used to show the underlying class that the object will belong to. Please note that all the variables that have been initiated with single, double, or triple quotes are taken as string. You can use single and double quotes for a single line of characters. Multiple lines are generally put in triple quotes.

String common methods

  • Get the index of a substring in a string.
    # find the index of a "c" in a string "abcde"
    >>>  "abcde".index("c")
    2
    

2 is returned because the position of the individual letters in the strings is 0-indexed. So, index of "a" in "abcde" is 0, that of "b" is 1, and so on.

  • Test if a substring is a member of a larger string. This is done using the keyword in and writing the test. The skeleton is shown below.

    substring in string

    >>> # for example, test if string "i" is present in string "pythonic" at least once. "i" is present in the string. Therefore, the result should be true.
    >>>  "i" in "pythonic"
    True
    >>> # as "x" is not present in the string "pythonic" the below test should return false
    >>> "x" in "pythonic" # "x" is not present in "pythonic"
    False
    
  • Join a list of strings using the join method. A list of strings is written by delimiting the sequence with a comma ,, and enclosing the whole group with brackets [...]. For a more detailed tutorial on lists head over to the python lists tutorial. You can join a list of strings by giving the delimiter as the object on which the method join will act and the list of strings as the argument.

    >>> # join a list of strings 1, 2, 3 with a space as a delimiter and 1,2,3 as the list of strings. So, the result will be the strings with spaces between them.
    >>>  combined_string = " ".join(["1", "2", "3"])
    '1 2 3'
    
  • Break a string based on some rule. This takes in the string as the object on which the method split is passed using the dot operator. Splitting takes a space as the default parameter.

For example you can split a string based on the spaces between the individual values.

    >>> # split the string "1 2 3" and return a list of the numbers.
    >>>  "1 2 3".split() # splitting
    ['1', '2', '3']

Or you can split a string based on a delimiter like :.

     >>> “1:2:3”.split(“:”)
     [‘1’, ‘2’, ‘3’]
  • Access individual characters in a string. Note the first element has index 0. You access the first element with the index 0, second element with the index 1, and so on.
    >>>  lang = "python"
    >>>  print(lang[0])
    >>>  print(lang[2]) # access the 3rd letter
    't'
    >>>  print(lang[-3]) # access the third letter from the end.
    'h'
    

Formatting in String:

String object can be formatted. You can use %s as a formatter which will enable you to insert different values into a string at runtime and thus format the string. The %s symbol is replaced by whatever is passed to the string.

    >>>  print("I love %s in %s" % ("programming", "Python")) # templating strings
    'I love programming in Python'

You can also use the keyword format. This will enable you to set your own formatters instead of %s.

>>> print("I love {programming} in {python}".format(programming="programming", python="Python"))
'I love programming in Python'

Truth value testing of String

A string is considered to be true in Python if it is not an empty string. So, we get the following:

# Test truth value of empty string
>>>  print(bool(""))
False

# Test truth value of non-empty string "x"
>>>  print(bool("x"))
True
Contributed by: Joydeep Bhattacharjee
Notifications
View All Notifications

?