Strings are the most important data types in Python. The string is defined as a combination of more than one character placed contiguously within quotation marks. In other programming languages a string is enclosed only in double quotes but in python, we have the freedom to put our string in either double or single quotes. Python treats single quote same as double quotes.
>>> 'CodeInPython' CodeInPython >>> "CodeInPython" CodeInPython
Creating a string is quite simple you just have to put a combination of characters within quotes and then assign it to a variable.
x = "Welcome to CodeInPython" print(x)
Accessing element in Strings
Now for people who already have a background in other programming languages are already familiar with the concept of arrays. Well, an array is a collection of data items, all of the same type and is accessed using an index.
For example, int arr creates an array of 10 integer variables all of them can only store integer values. The variables have same name arr but are different with the use index or their position in an array which begins with 0. Therefore, arr = 10 is the first array element to store an integer of value 10, arr = 12 is second array element, arr is third and so on.
Now accessing an element in the string follows a similar concept. Let our string variable be y = “Hello”. Now to access letter ‘e’ we will call y. We can use the same concept of index or position of elements. Index in string starts from 0 and the last letter will have (str length – 1) index.
Differentiate between double and single quote
Let say there is string
z = I’ll learn Python
and we decide to put this string in single quotes. It will look like this
z = 'I'll learn Python'
The problem in this situation is it will only read the letter ‘I’ since quotes begin before ‘I’ and end after it. The characters after ‘I’ will not be stored in a variable. Now there are two ways to tackle this problem.
1) Using escape sequence: Place an escape character ‘\’ (backslash) before the single quote if it has to be read along with the string.
z = 'I\'ll learn Python'
By using escape sequence you will be able to store the whole sentence within the variable z
2) Interchange double and single quotes: Another way to avoid this problem is to interchange double and single quotes.
z = "I'll learn Python" y = 'He said, "He will learn Python" '
Newline in Strings
An escape sequence \n is used in quotes along with the string to push the statement or the sentence in a new line.
x = "You like \n CodeinPython" print(x)
Sometimes there is need to input or display the string as it is without changing anything. In such situations, strings need to be used in their raw form. To get raw string just place lowercase letter ‘r’ in front of the whole string.
>>> print(r"C:\User\newfolder") C:\User\newfolder