String
String
Python string is the collection of the characters surrounded by single quotes, double quotes,
or triple quotes. The computer does not understand the characters; internally, it stores
manipulated character as the combination of the 0's and 1's.
Creating String in Python
We can create a string by enclosing the characters in single-quotes or double- quotes.
Python also provides triple-quotes to represent the string, but it is generally used for
multiline string.
Example
1. #Using single quotes
2. str1 = 'Hello Python'
3. print(str1)
4. #Using double quotes
5. str2 = "Hello Python"
6. print(str2)
7.
8. #Using triple quotes
9. str3 = '''''Triple quotes are generally used for
10. represent the multiline or
11. docstring'''
12. print(str3)
H E L L O S T U D E N T
0 1 2 3 4 5 6 7 8 9 10 11 12
IF read left to right it will start from 0
-13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
If we read right to left from -1
# declaring the string
str = "Hello student"
# accessing the character of str at 0th index
print(str[0])
# accessing the character of str at 6th index
print(str[7])
# accessing the character of str at 10th index
print(str[10])
Output
H
T
E
Accessing Characters by Negative Index Number: In this type of Indexing, we pass the
Negative index(which we want to access) in square brackets. Here the index number starts
from index number -1 (which denotes the last character of a string).
Negative Slicing
print(my_list[-4:-1]) # Output: [20, 30, 40]
print(my_list[::-1]) # Output: [50, 40, 30, 20, 10] # Reverses the list
Syntax :
H=”Hello student” H is a varlable
Print(H[4]) output is =o
Print(H[0:7]) this is range in which multiple characters it show hello
If we use
Print(H[o:]) it read all characters
If we use
Print(H[o: :2]) it show 2 increment means it read one skip character
# String slicing
String = 'welcome'