What are Strings in Python | Python Strings with Examples

A string is a sequence of characters and a character is a symbol be it an alphabet, special character etc. Similar to how integers are converted to binary values by the compiler, characters are converted to Unicode values in Python.

These Unicodes range from 0hex to 10FFFFhex. Normally, a Unicode is referred to by writing “U+” followed by its hexadecimal number. Thus strings in Python are a sequence of Unicode values. 

strings in python

By now, you must have been wondering……

Why not ASCII? Why Unicode?

Both ASCII & Unicode are formats used by the compiler to encode strings. ASCII can represent a very limited set of alphabets or symbols like lowercase letters (a-z), uppercase letters (A-Z), digits(0-9), Symbols (,) etc. But unlike ASCII, Unicode is more generalized and consists of a value for every possible character in every possible language. Also, today’s applications display messages which use a wide variety of languages and symbols. Considering this, Unicode is a better choice for encoding. If you want to know more about Unicode, then check this.

 

Things about Strings (Must Know)

Now, let us learn how to assign, access and perform various operations on Strings.

How to Initialize/Assign a String to a Variable

In Python, strings can be assigned by either using single or double or triple quotes as shown below.

#assigning using single quotes
string1 = 'Welcome'

#assigning using double quotes
string2 = "to"

#assigning using triple quotes
string3 = '''FACE Prep's Python Programming Tutorial'''

print(string1)
print(string2)
print(string3)
Output:
Welcome
to
FACE Prep's Python Programming Tutorial
If we assign a string in single quotes and if the string inturn contains single-quoted character in it, then an error is thrown by the compiler as it doesn’t know the start and end of the string.
#assigning a string containing quotes

string1 = 'Welcome to 'Python' course'
print(string1)
Output
File "main.py", line 1
    string1 = 'Welcome to 'Python' course'
                                ^
SyntaxError: invalid syntax

In such cases, it is advisable to use double-quotes to avoid all the confusion. Now, let’s use double quotes and see if the string gets printed.

string1 = "Welcome to 'Python' course"
print(string1)
Output
Welcome to 'Python' course

Similarly, for strings that contain Double quoted words in them, the use of triple quotes or single quotes is recommended.

Also, you can easily assign a multiline string in Python using 3 double quotes or 3 single quotes at the beginning and end of a string. An example of this is shown below.

#assigning multiline strings in Python
string1 = """Welcome
to
FACE Prep's 
Python Programming Tutorial"""

print(string1)
Output:
Welcome
to
FACE Prep's 
Python Programming Tutorial

How to Access Characters in a String

a) Accessing Single Characters

Single characters in a string can simply be accessed using the index of that character. If you try to access a character that is out of range, then the compiler will throw an error. Also, the indexed value must be an integer.

#accessing single character of a string
string1 = "FACE Prep's Python Tutorials"
print(string1[1]) # prints the character at the index 1, i.e prints the character 'A'

print(string1[27]) # prints the character at the index 27

print(string1[-1]) #prints the character at the index -1, i.e the first character from the end.
Output:
A
s
s
Some false indexing methods that would lead to errors are:
1) Using an out of range index value
 
#accessing single character of a string
string1 = "FACE Prep's Python Tutorials"
print(string1[28]) 
2) Using a non-integer index value
 
#accessing single character of a string
string1 = "FACE Prep's Python Tutorials"
print(string1[3.0])

So accessing of characters in a string is pretty straightforward. Now, let’s look at accessing multiple characters or words in a string.

b) Accessing Multiple Characters

Consider, the same string “FACE Prep’s Python Tutorials”. Say, for example, you need to print only the word “Python”. This can be be done using the slicing operator (:). The syntax for performing slicing is given below.

Syntax: stringname (starting index : ending index)
where the starting index is inclusive & ending index is exclusive.

#accessing a part of the string
string1 = "FACE Prep's Python Tutorials"
print (string1[12:18])
print (string1[-12:-2])
Output:
Python
on Tutoria

Explanation: In the specified range 12 to 18, the compiler prints the character at index 12 and doesn’t print the character at index 18. 

How to Modify/Update a String

In Python, strings are immutable. This means once initialized, you cannot modify any part of the string. Rather you can delete or assign a new string to the same variable. This is demonstrated below. 

#modifying a string
string1 = "FACE Prep"
string2 = "Python Tutorials"

#by assigning a new string
string1 = "New FACE Prep"
print (string1)

#by deleting the string
del string2
print (string2)
Output:
New FACE Prep
Traceback (most recent call last):
  File "main.py", line 11, in <module>
    print (string2)
NameError: name 'string2' is not defined
 
Explanation: Since string2 has been deleted, the compiler throws an error. This means the output is right.
 
 

Other Important Concepts of Strings in Python

a) Escape Sequence

As you know by now, we cannot print a string containing single quotes using single quotes and the same is the case for double quotes/triple quotes when the string to be printed contains double/triple quotes in it. To help in dealing with such cases, the escape sequence comes into the picture. An escape sequence starts with a backslash (\) followed by a character.

Escape sequence indicates the compiler that the character followed by \ should be simply ignored. For instance,

#escaping single quote 
string1 = 'I\'m in love with Python Language'
print(string1)
Output:
I'm in love with Python Language
Also, you can tell the compiler to ignore the escape sequence by placing a r or R before your string. this way a raw string can ignore escape sequence. This will be useful when the string to be printed contains a backslash (\).
#escaping the escape sequence
string1 = R'I would prefer learning Python\Java\Both'
print(string1)
Output: 
I would prefer learning Python\Java\Both
 

b) Operations on Strings in Python

A lot of operations can be performed on strings and some of them are listed below. In each of these operations, consider that

a = “FACE Prep”
b = “Python Tutorials”

OperationOperatorSample ProgramOutput
String Concatenation: Addition of two strings+print (a+b)FACE PrepPython Tutorials
String Repetition: Multiplies the same string by a given number of times*print (a*2)FACE PrepFACE Prep
String Membership: Check if the given a character is a part of the stringin, not inprint (‘f’ in ‘a’)
print (‘f’ not in ‘a’)
False
True

c) String Formatting

In Python, we cannot directly add a value of one data type to another. Something like this,

a = 5
b = "My name is XYZ & my age is just" + a
print(b)
Output: 

Traceback (most recent call last):
File "main.py", line 2, in <module>
b = "My name is XYZ & my age is just" + a
TypeError: can't convert int object to 'str' implicitly

In such cases, we can either go for type conversion or use Format () method in Python. The format() method takes the arguments or variables which are passed, formats them, and places them in the string wherever the placeholders {} symbol is used.

For example, lets see how the above example can be formatted.

a = 5

#single formatting
b = "My name is XYZ & my age is just {}"
print (b.format(a))

#multiple formatting
c = "My name is XYZ & my age is just {}. Also I have a sibling who's age is also {}"
print(c.format(a, a))
Output:
My name is XYZ & my age is just 5
My name is XYZ & my age is just {}. Also I have a sibling who's age is also 5
In fact, to avoid confusion, you can index these arguments.
#multiple formatting with indexing
c = "My name is {2} & my age is just {0}. Also I have a sibling who's age is {1}"
print(c.format(5, 8, "XYZ"))
Output: 
My name is XYZ & my age is just 5. Also I have a sibling who's age is 8

d) String Methods

These are a set of most used built-in methods that you can use on strings to perform some simple operations.

MethodDescription
upper ()Converts a string into Upper case
lower ()Converts a string into lower case
join ()Joins the elements of an iterable to the end of the string
split ()Splits the string at the specified separator
find ()Searches the string for a specified value and returns the position of that value
replace ()Replaces a specified value in a string with another specified value