Strings are used to represent text in Python.
A string is a sequence of characters enclosed in single quotes (') or double quotes (").
Creating Strings
Example:
name = "John"
city = 'London'
print(name)
print(city)
Output:
John
London
Strings are Arrays
Strings in Python are arrays of characters.
Example:
text = "Python"
print(text[0])
Output:
P
Loop Through a String
You can loop through the characters of a string using a for loop.
Example:
text = "Python"
for char in text:
print(char)
Output:
P
y
t
h
o
n
String Length
Use the len() function to get the length of a string.
Example:
text = "Hello"
print(len(text))
Output:
5
Check if a String Contains Text
Use the in keyword to check if a string contains a specific word or character.
Example:
text = "Python Programming"
print("Python" in text)
Output:
True
Check if a String Does Not Contain Text
Use the not in keyword.
Example:
text = "Python Programming"
print("Java" not in text)
Output:
True
String Slicing
You can return a range of characters using slicing.
Example:
text = "Python"
print(text[0:4])
Output:
Pyth
Slice From the Beginning
Example:
text = "Python"
print(text[:4])
Output:
Pyth
Slice to the End
Example:
text = "Python"
print(text[2:])
Output:
thon
Negative Indexing
Negative indexes start from the end of the string.
Example:
text = "Python"
print(text[-1])
Output:
n
Modify Strings
Strings are immutable, but you can create a modified copy.
Convert to uppercase:
text = "hello"
print(text.upper())
Output:
HELLO
Convert to lowercase:
text = "HELLO"
print(text.lower())
Output:
hello
Remove Whitespace
Use the strip() method.
Example:
text = " Hello "
print(text.strip())
Output:
Hello
Replace Text
Use the replace() method.
Example:
text = "Hello World"
print(text.replace("World", "Python"))
Output:
Hello Python
Split Strings
The split() method splits a string into a list.
Example:
text = "Apple,Banana,Mango"
print(text.split(","))
Output:
['Apple', 'Banana', 'Mango']
Concatenate Strings
Use the + operator to combine strings.
Example:
first = "Hello"
second = "World"
print(first + " " + second)
Output:
Hello World
Escape Characters
Use the backslash (\) to insert special characters.
Example:
text = "It's alright"
print(text)
Output:
It's alright
Or:
text = 'It\'s alright'
print(text)
Output:
It's alright
Summary
- Strings are used to store text.
- Strings can be created with single or double quotes.
- Strings are arrays of characters.
- Use indexing and slicing to access characters.
- Use methods like
upper(),lower(),strip(),replace(), andsplit(). - Use
+to join strings. - Strings are immutable and cannot be changed directly.