Strings in Python
Strings in Python
Note: Generally, to create a string mostly used syntax is double quotes syntax.
When triple single and triple-double quotes are used?
If you want to create multiple lines of string, then triple single or triple-double quotes are the
best to use.
Indexing:
Indexing means a position of string’s characters where it stores. We need to use square
brackets [] to access the string index. String indexing result is string type. String indices
should be integer otherwise we will get an error. We can access the index within the index
range otherwise we will get an error.
Python supports two types of indexing
1. Positive indexing: The position of string characters can be a positive index
from left to right direction (we can say forward direction). In this way, the starting
position is 0 (zero).
2. Negative indexing: The position of string characters can be negative
indexes from right to left direction (we can say backward direction). In this
way, the starting position is -1 (minus one).
Diagram representation
Note: If we are trying to access characters of a string without of range index, then we will get
an error as IndexError.
Example:
Different Cases:
wish = “Hello World”
1. wish [::] => accessing from 0th to last
2. wish [:] => accessing from 0th to last
3. wish [0:9:1] => accessing string from 0th to 8th means (9-1) element.
4. wish [0:9:2] => accessing string from 0th to 8th means (9-1) element.
5. wish [2:4:1] => accessing from 2nd to 3rd characters.
6. wish [:: 2] => accessing entire in steps of 2
7. wish [2 ::] => accessing from str[2] to ending
8. wish [:4:] => accessing from 0th to 3 in steps of 1
9. wish [-4: -1] => access -4 to -1
Note: If you are not specifying the beginning index, then it will consider the beginning of the
string. If you are not specifying the end index, then it will consider the end of the string. The
default value for step is 1
Example: Slicing operator using several use cases (Demo11.py)
wish = "Hello World"
print(wish[::])
print(wish[:])
print(wish[0:9:1])
print(wish[0:9:2])
print(wish[2:4:1])
print(wish[::2])
print(wish[2::])
print(wish[:4:])
print(wish[-4:-1])
Output:
Output2:
Output: True
Example: To check space importance in the string at the end of the string (Demo23.py)
s1 = "abcd"
s2 = "abcd "
print(s1 == s2)
if(s1 == s2):
print("Both are same")
else:
print("not same")
Output:
Note: These methods won’t remove the spaces which are in the middle of the string.
Example: To remove spaces in the string and end of the string in python
(Demo24.py)
find() method:
Syntax– nameofthestring.find(substring)
T
his method returns an index of the first occurrence of the given substring, if it is not available,
then we will get a -1(minus one) value. By default find() method can search the total string of
the object. You can also specify the boundaries while searching.