Strings in Python

A String contains textual data in the form of an indexed and unchangeable sequence of characters. It can be used as a value of a variable or to write a message or sentence in a program.

Since a computer is aware of the binary language only ie 0 and 1, the characters of a string are ultimately Unicode characters. Therefore, a string can also be seen as an array of Unicode characters.

This article will tell you about:

Creating a string in Python

To create a string, the sequence of characters is placed inside a pair of double quotes. The quotation marks represent the beginning & end of the string.

Syntax:
" Sequence of characters "

  • A string can be directly printed using print().
    Example:
    print("I am learning Python Strings.")​

    Output:
    I am learning Python Strings.​
  • A string can be assigned as a value to a variable.
    Example:
    name = "Kriti Jain"
    print(name)​

    Output:
    Kriti Jain​

Note: Unlike other languages, Python does not have the character datatype. So, you can create a string with a single character and use it as a character.

Accessing the characters of the string in Python

Every character of a string has an index that represents its position in the string. You can access each character of the string using its index. To access the character, its index is mentioned within the square brackets.

Syntax:
string_name[index]

There are three ways to access a string with the help of the index.

  1. Using Positive Index:

    The positive indexing in a string starts from the first character with index 0.

    Example:

    day = "monday"
    print("day =", day)
    print("Index 2 :", day[2])​

    Output:
    day = monday
    Index 2 : n​
  2. Using Negative Index:

    The negative indexing starts from the last character with index -1 and proceeds towards the left in the string.

    Example:

    day = "monday"
    print("day =", day)
    print("Index -1 :", day[-1])

    Output:

    day = monday
    Index -1 : y
  3.  Using Slice:

    A part of the string can be accessed using the slice feature in python. You need to specify the beginning and end of the portion you want to access. The slice does not include the last item of the range provided.

    Example:

    day = "monday"
    print("day =", day)
    print("day[1:4] =", day[1:4])

    Output:

    day = monday
    day[1:4] = ond

Formatting a string in Python

In Python, you can modify the appearance of a string. There are multiple ways to format a string.

1. Inserting Double quotes or apostrophe as a character in the string.

  • Using double quote while creating a string is considered as the standard way. But string can also be created using single or triple quotes.
    If you want to create a string like, He said, "I am going to Chennai.", then you cannot use double quotes to create the string. In such cases, you must use single or triple quotes.
    Example:
    print("He said, "I am going to Chennai."")​

    Output: This code raises a syntax error. 
    SyntaxError: invalid syntax​

    Now, let us replace the outer double quote with single quotes.
    Example:
    print('He said, "I am going to Chennai."')​

    Output
    He said, "I am going to Chennai.​
  • In case you want to insert an apostrophe in your string like This is the school's property., then you cannot use single quotes to create a string.
    Example:
    print('This is the school's property.')​

    Output: This code raises a syntax error. 
    SyntaxError: invalid syntax​
    In this case, you will have to replace the outer single quotes with a double quote.
    Example:
    print("This is the school's property.")​

    Output:
    This is the school's property​.

2. Inserting multiples lines in a string with the help of triple quotes. 

Example:

print("""Python allows you to
insert multiple
lines in
a String.""")

Output:

Python allows you to
insert multiple
lines in
a String.

3. Escape Sequences

The characters which have a special meaning to the interpreter are known as Escape sequences. They are used to perform some special task in the code. Following escape sequences are available in Python:

Escape Sequence Meaning
\' Insert a single quote
\" Insert a double quote
\\ Insert a backslash
\n Insert a new line
\t Insert a tab
\b Insert a backspace
\c Insert a carriage return
\v Insert a vertical tab
\f Insert a formfeed

Raw String in Python

A raw string is a string with no formatting. If you have created a formatted string and afterwards there is a need for the unformatted string, you can use the raw string.

To make a string raw, you need to insert r or R right before the first quotation mark of the string. This causes the interpreter to forget the special meaning of escape sequences, formatting symbols etc and they are treated like the ordinary characters of the string itself.

Syntax:
r"string"

Example:

#without r
print("This is the school\'s property.")
#with r
print(r"This is the school\'s property.")

Output:

This is the school's property.
This is the school\'s property.

Changing the characters of the string in Python.

A string is an immutable datatype ie it can not be modified. Though you can reassign a string with a new value but it is not possible to change the characters of the string separately. An error will be faced if you try to change any character of the string.

Example:

day = "monday"
print("day =", day)
day[2] = "t"

Output:

TypeError: 'str' object does not support item assignment

Deleting a String in Python.

You can delete the whole string with the help of del keyword. You just have to mention the name of the string which has to be deleted.

Syntax:
del string_name

Example:

day = "monday"
del day #deleting the string
print(day)

Output:

NameError: name 'day' is not defined

Length of a String in Python.

len() function finds out the length of a string when you pass the string name as the parameter to it. Length of the string is an integer which represents the number of characters present in the string.

Syntax:
len(string_name)

Example:

day = "monday"
print("String =", day)
print("Length of the string = ", len(day))

Output:

String = monday
Length of the string = 6

For Loop with Python String

You can use for loop to visit and access each character of a string one by one.

Syntax:
for x in string_name:
     body of the loop

Example:

day = "monday"
for x in day:
    print("day[",day.index(x),"] =", x)

Output:

day[ 0 ] = m
day[ 1 ] = o
day[ 2 ] = n
day[ 3 ] = d
day[ 4 ] = a
day[ 5 ] = y

Concatenation and multiplication of strings.

Like Lists and tuples, strings can also be concatenated or multiplied using + and * operators.

  • Concatenation: The + operator joins two or more than two strings, end to end and a new string is created. You can directly concatenate the strings or you can use the variables that refer to the strings.

    Example:

    day1 = "monday"
    day2 = "tuesday"
    print("day1 =", day1)
    print("day2 =", day2)
    print("day1 + day2 =", day1 + day2)
    print('"Hello! " + day1 =', "Hello! " + day1)

    Output:

    day1 = monday
    day2 = tuesday
    day1 + day2 = mondaytuesday
    "Hello! " + day1 = Hello! monday
  • Multiplication: The * operator multiplies a string by the given number of times. The copy of the string is added to the end of the previous string.

    Example:

    day = "monday"
    print("day =", day)
    print("day * 4 =", day * 4)

    Output:

    day = monday
    day * 4 = mondaymondaymondaymonday

String methods in Python

String methods are the built-in functions provided by python. With these functions, you can manipulate and format the strings. There are various methods available which let you test different properties of the strings like length, type of characters, lowercase or uppercase alphabets etc.
The article Python - String Methods will provide you with the list of String methods & their examples.