Strings

Strings in Python can be used to store a contiguous set of characters. To define a string, you simple type the characters within single or double quotes. For example, newString = ‘Hello world!’ will store that string of characters (Hello world!) in the variable called newString:

>>> newString = 'Hello world!'
>>> print (newString)
Hello world!

You will get the same result if you use the double quotes to define a string:

>>> newString = "Hello world!"
>>> print(newString)
Hello world!

The reason why both forms are used is so you can embed a quote character of the other type inside a string. For example, you may embed a single-quote character in a string enclosed in double-quote characters:

>>> newString = "Mark's car"
>>> print(newString)
Mark's car

Note that you can not perform numeric operations with string variables, even if the string stored in the variable consists only of numbers. Consider the following example:

>>> x = '5'
>>> y = '3'
>>> print(x + y)
53

The + operator concatenates two strings. To perform an arithmetic operation, we need to convert the string variables to integer or floating-point variables:

>>> x = int('5')
>>> y = int('3')
>>> print(x + y)
8
Geek University 2022