A string is used to store text in Python.
Anything written inside single quotes ' ' or double quotes " " is considered a string.
Examples of strings:
- Names
- Cities
- Messages
- Email addresses
- Sentences
Strings are one of the most frequently used data types in programming.
You can create strings using single or double quotes.
name = "Arjun"
city = 'Mumbai'
message = "Welcome to Python"Both single and double quotes work the same way.
print("Hello World")Printing a variable:
name = "Riya"
print(name)Each character in a string has a position (index).
Important rule:
- Index starts from 0
Example:
text = "Python"
print(text[0])
print(text[1])Output:
P
y
Index positions:
P y t h o n
0 1 2 3 4 5
Python also supports negative indexing.
-1means last character-2means second last
Example:
text = "Python"
print(text[-1])Output:
n
Slicing allows you to extract part of a string.
Syntax:
string[start:end]
Example:
text = "Programming"
print(text[0:6])Output:
Progra
Important:
- Start index is included
- End index is excluded
Another example:
print(text[3:8])text = "Python"
print(text[:4]) # From start to index 4
print(text[2:]) # From index 2 to endConcatenation means joining strings.
Using + operator:
first = "Hello"
second = "World"
print(first + " " + second)Output:
Hello World
Use len() to count characters.
text = "Python"
print(len(text))Output:
6
- Trying to change a character directly
text = "Python"
text[0] = "J" # ErrorStrings are immutable (cannot be changed directly).
- Forgetting quotes
name = Rahul # Error- Wrong slicing index
- Create a string with your city name
- Print the first character
- Print the last character
- Print first 3 characters
- Join two strings using
+ - Print length of a string
Example practice:
city = "Delhi"
print(city[0])
print(city[-1])
print(city[:3])
print(len(city))