In Python, a string (str) is an immutable sequence of Unicode characters used to store and represent text.
1. Creating Strings
Strings in Python can be created using either single quotation marks or double quotation marks. We can also use triple quotes to create multiline strings.
single = 'hello'
double = "World"
multi_line = """Triple quotes let us write strings
that span multiple lines."""
2. Indexing and Slicing
Strings are zero-indexed, meaning the first character starts at index 0.
You can also use negative indexing to access characters from the end. The index -1 represents the last character.
text = "Python"
# Indexing
print(text[0]) # Output: P
print(text[-1]) # Output: n
# Slicing [start:end:step]
# The end index is excluded
print(text[0:2]) # Output: Py
print(text[2:]) # Output: thon
print(text[-1::-1]) # Output: nohtyP
3. Immutability
Strings are immutable, which means we cannot change their characters directly after creating them.
Any operation that modifies a string actually creates and returns a new string.
name = "Python"
# Trying to change a character
# name[0] = "J" # TypeError
# Creating a new string
name = "J" + name[1:]
print(name) # Output: Jython
Notice that we didn't modify the original string. Instead, we created a new string and assigned it to the variable name.
4. String Concatenation
Concatenation means joining two or more strings together using the + operator.
first = "Hello"
second = "World"
result = first + " " + second
print(result) # Output: Hello World
We can also use the * operator to repeat a string.
word = "Python "
print(word * 3) # Output: Python Python Python
5. String Length
Python provides the built-in len() function to find the number of characters in a string.
text = "Python"
print(len(text)) # Output: 6
Remember that spaces and special characters are also counted.
6. Common String Methods
Python provides several built-in string methods to perform common operations.
text = " Hello Python "
print(text.upper()) # HELLO PYTHON
print(text.lower()) # hello python
print(text.strip()) # Hello Python
print(text.replace("Python", "World"))
# Hello World
print(text.startswith(" Hello")) # True
print(text.endswith(" ")) # True
These methods return new strings. They do not modify the original string.
Top comments (0)