Python Variable & Data Type
Python Strings
Learn Python Strings with clear explanations, Python examples, and practical programming guidance.
What is a string in Python?
A string is an ordered sequence of text characters. It can contain letters, numbers, punctuation, spaces, Unicode characters, and emojis. Python does not have a separate character type, so one character is simply a string with length one.
Creating strings
Use matching single or double quotation marks. Choose the style that lets you include the other quote without unnecessary escaping:
single_quoted = 'Python'
double_quoted = "Programming"
with_apostrophe = "Python's syntax is readable"
print(single_quoted)
print(double_quoted)
print(with_apostrophe)
print(type(single_quoted))Programming
Python's syntax is readable
<class 'str'>
Multiline strings
Triple single or double quotes create a string that can span multiple lines. They are useful for long text and documentation strings:
message = """Learning Python
is easier when examples
are clear and practical."""
print(message)is easier when examples
are clear and practical.
Important characteristics of strings
| Characteristic | Meaning |
|---|---|
| Ordered | Each character has a position, starting at index 0. |
| Immutable | An existing string cannot be changed in place; operations return a new string. |
| Iterable | You can visit each character with a for loop. |
| Sliceable | You can extract part of a string with text[start:end]. |
| Unicode-aware | Python 3 strings support text from many languages and symbols. |
Accessing characters with indexes
Indexes start at zero from the left. Negative indexes count backward from the end, where -1 is the last character:
text = "Python"
print(text[0])
print(text[2])
print(text[-1])
print(text[-2])t
n
o
An index outside the valid range raises IndexError. Indexes must be integers.
String slicing
Slicing extracts a range using the form text[start:stop:step]. The start index is included, but the stop index is excluded:
text = "Python"
print(text[1:4]) # characters at indexes 1, 2, and 3
print(text[:3]) # from the beginning
print(text[3:]) # from index 3 to the end
print(text[::2]) # every second character
print(text[::-1]) # reversed stringPyt
hon
pto
nohtyP
Strings are immutable
You cannot replace one character directly inside an existing string. Create a new string using slicing, concatenation, or a method such as replace():
message = "welcome learners"
# message[0] = "W" # TypeError: strings cannot be changed in place
capitalized = "W" + message[1:]
updated = message.replace("learners", "Python developers")
print(capitalized)
print(updated)welcome Python developers
Useful string operations
| Operation | Example | Result or purpose |
|---|---|---|
| Length | len("Python") | Returns 6. |
| Concatenation | "Py" + "thon" | Combines strings. |
| Repetition | "ha" * 3 | Produces "hahaha". |
| Membership | "Py" in "Python" | Returns True. |
| Case conversion | text.upper() | Returns a new uppercase string. |
| Whitespace removal | text.strip() | Removes leading and trailing whitespace. |
first = "Py"
second = "thon"
print(first + second)
print("ha" * 3)
print(len("Python"))hahaha
6
Common string methods
String methods do not modify the original string. They return a new value:
text = " Learning Python is fun! "
print(text.strip())
print(text.upper())
print(text.lower())
print(text.replace("fun", "useful"))
print("Python,Java,SQL".split(","))
print("-".join(["Python", "Java", "SQL"]))strip() removes outer whitespace, upper() and lower() change case, replace() substitutes text, split() creates a list, and join() combines an iterable of strings.
Checking and searching text
text = "Python programming"
print(text.startswith("Python"))
print(text.endswith("ing"))
print(text.find("program"))
print(text.count("m"))
print(text.isalpha())
print("123".isdigit())Methods such as startswith(), endswith(), find(), and count() help search text. Validation methods such as isalpha() and isdigit() inspect the contents of a string.
Concatenation and formatting
Use + for simple concatenation. For messages containing several values, f-strings are usually the clearest option:
name = "Asha"
age = 25
city = "Pune"
message = f"{name} is {age} years old and lives in {city}."
print(message)The older format() method is still useful in existing code:
message = "{} works with {}.".format("Asha", "Python")
print(message)Escape characters and raw strings
Escape sequences represent special characters inside a quoted string:
print("First line
Second line")
print("Column 1 Column 2")
print("She said, "Hello!"")
print("C:\Users\Asha")A raw string treats backslashes mostly as ordinary characters, which is convenient for regular expressions and Windows-style paths:
path = r"C:UsersAsha
otes.txt"
print(path)Testing membership
Use in and not in to check whether a character or substring exists:
text = "Python programming"
print("Python" in text)
print("Java" in text)
print("SQL" not in text)False
True
Deleting a string name
You cannot delete one character from an immutable string, but del can remove the variable name from its namespace:
message = "Hello"
del message
# print(message) # NameError: message is no longer definedBest practices for Python strings
- Use clear quotation styles and escape quotes only when necessary.
- Remember that methods return new strings because strings are immutable.
- Use f-strings for readable messages that include variables.
- Use
strip()and validation methods when processing user input. - Use
join()instead of repeatedly concatenating many strings in a loop. - Use Unicode text directly in Python 3 and choose an explicit encoding when reading or writing files.
Further Reading
Continue learning with these related Python tutorials:
Continue learning
