Strings in Python Part-1
What is string?
- It’s an ordered Sequence. And Python keeps track of every element in the string as sequence.
- for Example :
- We have written ‘HELLO’ then Python understands the string to be in specific order. Which means we will be able to use indexing to grab particular letters.
Note : I am using Jupyter notebook and because of which without using print() function getting the output. But correct way to display string is using print() function.
How to create a string?
we can create a string in Python using single quotes and Double Quotes
- for Example:
Be aware with quotes!
- In the above 1.2 reason for the error is single quote in I’m stopped the string.
We can use combination of single quotes and double quotes to get desired output. as shown in 1.3
Multiline Strings
can assign a multiline string to a variable by using three quotes
How to print a string?
- We can use print () function
- for Example:
Use of len() function to check the length of the string!
Python’s built-in len() function counts all of the characters in the string, including spaces and punctuation.
How to do Indexing in String?
we know strings are in ordered sequence. and we can use those indexes to call parts of it.
here, [ ] square bracket is used after an object to call it’s Index. Important note is Indexing start from 0 in python.
we can also access a string by negative indexing. which starts from -1
Now How to grab all the element together or to grab some specific part of it?
so for that we can use slicing to achieve this task.
mystring[-1] means the last letter (one index behind 0 so it loops back around)
step size in more detail:
String Properties:
It has most important property of Immutability. Which means once the string is created, we can not change the elements within it.
for example:
We can’t slice the string and get the information but we can concate the string
We can use the multiplication symbol to create repetition!