Python Datatypes: Strings
A string is a sequence of characters that is created using a single coat or double coat. As in the example below.
‘Rakesh’
“My name is John”
You can also use indexing in strings. Such as in the example below.
Alpahbets: J o h n G e o r g e
Index: 0 1 2 3 4 5 6 7 8 9 10
Alpahbets: R a c e s h
Index: 0 1 2 3 4 5
If the string is too large and contains too many alphabets, in that case we can use the -1 index for the final alphabets or characters. Space characters are also indexed in strings.
We can also print part of the entire string separately. This is called slicing.
Scape characters are also used in Python language. Some examples are: \n , \t .
\n: This character is also called newline character. When we print a string, if we add this newline character in the middle of it, then any text that follows this new line will be printed in the next line.
The Python language also has a lot of built-in functions. One of them is the function len(), which can be used for strings.
Below we’ll look at string operations.
We have created a variable named na1. To whom we have assigned the value “John George”. As mentioned earlier “John George” is a string, so on this we will see examples of indexing below.
We printed the index zero of the na1 variable using python’s print function. His result came alphabet J.
na1 = “John George”
print(na1[0])
>> J
Now use the print statement above in your program and keep changing the value of the induction. O print when you keep the value of indexing to one. When you keep the value of indexing at 3, n will be printed.
If you put the value of indexing to -1, then the last character of that string will be printed. So keeping the index value -1 in the print statement given above will be e-printed.
In the case of slicing, more characters are printed instead of printing one character of the screen. A simple example of this is given below
na1 = “John George”
print(na1[5:])
>> George
Recent Comments