
String data types in Python
Python provides the str type for working with text: from greetings to file parsing. In this article we'll cover how to create strings, what operations and methods they have, and how to neatly insert variable values into text.
What are strings in Python?
Strings (type str) are sequences of characters used to store and process textual information.
How to create strings in Python
Python offers several ways to create strings. You can use single, double, or triple quotes:
Python 3.13# Strings in single quotes single_quotes = 'Hello, world!' print(single_quotes)Hello, world!# Strings in double quotes double_quotes = "Python is fun" print(double_quotes)Python is fun# Multi-line strings in triple quotes multi_line = """Coffee recipe: 1. Boil water 2. Pour over the ground coffee 3. Wait 4 minutes""" print(multi_line)Coffee recipe: 1. Boil water 2. Pour over the ground coffee 3. Wait 4 minutes
The choice of quote type depends on the situation:
- Single (') and double (") quotes work the same way
- If the string already contains single quotes, it's easier to wrap it in double quotes, and vice versa
- Triple quotes (""" or ''') are good for multi-line text
Escaping characters
Sometimes we need to include special characters in a string, such as quotes or a line break. Backslash sequences (\) handle this:
Python 3.13# Using quotes inside strings with escaping quote_inside = "He said: \"Hello!\"" print(quote_inside)He said: "Hello!"path = "C:\\Program Files\\Python" print(path)C:\Program Files\Python# Common escape sequences newline = "First line.\nSecond line." # \n - newline print(newline)First line. Second line.tab = "Name:\tJohn" # \t - tab print(tab)Name: John
Useful escape sequences:
- \n for a newline
- \t for a tab
- \\ for a backslash
- \' for a single quote
- \" for a double quote
Raw strings for paths and regular expressions
If you work with file paths or regular expressions, constantly escaping backslashes gets tedious. Python offers "raw" strings with the r prefix:
Python 3.13# A regular string requires a double backslash normal_path = "C:\\Users\\Username\\Documents" print(normal_path)C:\Users\Username\Documents# A raw string treats backslashes literally raw_path = r"C:\Users\Username\Documents" print(raw_path)C:\Users\Username\Documents
Raw strings simplify work with Windows paths and regular expressions.
Immutability of strings
Strings in Python are immutable. This means that once a string is created, you can't modify it "in place": every operation that looks like a modification actually creates a new string.
An attempt to change a character by index fails with an error:
Python 3.13language = "Python" try: language[0] = "J" except TypeError as e: print(f"Error: {e}")Error: 'str' object does not support item assignment
To get a "modified" string, you build a new one and assign it, either to the same variable or to another:
Python 3.13language = "Python" language = "J" + "ython" print(language)Jython
This rule applies to all string operations: +, .upper(), .replace() and others all return a new string instead of changing the original.
Basic string operations
Concatenation
You can concatenate strings with the + operator to build new ones:
Python 3.13first_name = "John" last_name = "Doe" full_name = first_name + " " + last_name print(full_name)John Doegreeting = "Hello, " + full_name + "!" print(greeting)Hello, John Doe!
Repetition
The * operator repeats a string multiple times:
Python 3.13border = "=" * 20 print(border)====================
String length
To get the number of characters in a string, use the built-in len() function:
Python 3.13word = "Python" print(len(word))6empty = "" print(len(empty))0
Accessing individual characters
Each character in a string can be accessed by its position (index). Indexing starts from 0, and negative indices count from the end:
![String indices and slices String "Python" indices: positive 0–5 above letters, negative -6…-1 below them. The slice word[1:4] highlights y, t, h](/_next/image?url=%2Fstatic%2FguidePage%2Fstring-data-types%2Findexing-en.webp&w=3840&q=50)
Python 3.13word = "Python" first_letter = word[0] second_letter = word[1] last_letter = word[5] print(f"First letter: {first_letter}") print(f"Second letter: {second_letter}") print(f"Last letter: {last_letter}")First letter: P Second letter: y Last letter: n# You can also use negative indices to count from the end last_letter = word[-1] second_last_letter = word[-2] print(f"Last letter (from the end): {last_letter}") print(f"Second to last letter: {second_last_letter}")Last letter (from the end): n Second to last letter: o
Getting part of a string (slices)
Python has a powerful tool for working with strings: slices. They let you extract substrings by specifying the start and end indices:
Python 3.13message = "Python Programming" # Slice syntax: string[start:end:step] # start is included, end is excluded first_word = message[0:6] # first 6 characters print(f"First word: {first_word}")First word: Pythonsecond_word = message[7:] # from index 7 to the end print(f"Second word: {second_word}")Second word: Programmingprefix = message[:6] # from the start up to (not including) index 6 print(f"Prefix: {prefix}")Prefix: Pythonevery_second = message[::2] # every second character print(f"Every other letter: {every_second}")Every other letter: Pto rgamnreversed_string = message[::-1] # string in reverse print(f"In reverse: {reversed_string}")In reverse: gnimmargorP nohtyP
Slices are flexible:
- If you don't specify a start index, the slice begins at the start of the string
- If you don't specify an end index, the slice continues to the end of the string
- A negative step traverses the string in reverse
Useful methods for working with strings
Python provides many built-in methods for working with strings. Let's look at the most useful ones.
Changing the case of text
Python 3.13text = "Hello PYTHON world" upper_case = text.upper() print(f"Uppercase: {upper_case}")Uppercase: HELLO PYTHON WORLDlower_case = text.lower() print(f"Lowercase: {lower_case}")Lowercase: hello python worldtitle_case = text.title() print(f"Each word capitalized: {title_case}")Each word capitalized: Hello Python Worldcapitalized = text.capitalize() print(f"Only first letter capitalized: {capitalized}")Only first letter capitalized: Hello python world
Searching and replacing in strings
Python 3.13text = "Python is a great programming language" # Searching for a substring position = text.find("great") print(f"The word 'great' starts at position: {position}")The word 'great' starts at position: 13count = text.count("a") print(f"The letter 'a' appears {count} times")The letter 'a' appears 3 times# Checking the start and end of a string starts_with = text.startswith("Python") print(f"The string starts with 'Python': {starts_with}")The string starts with 'Python': Trueends_with = text.endswith("!") print(f"The string ends with '!': {ends_with}")The string ends with '!': False# Checking for a substring contains = "great" in text print(f"The string contains 'great': {contains}")The string contains 'great': True# Replacing substrings new_text = text.replace("great", "wonderful") print(f"Text after replacement: {new_text}")Text after replacement: Python is a wonderful programming language
Splitting and joining strings
Python 3.13# Splitting a string into a list of words sentence = "Python is a great programming language" words = sentence.split() print(f"List of words: {words}")List of words: ['Python', 'is', 'a', 'great', 'programming', 'language']# Splitting on a specific delimiter csv_data = "apple,banana,cherry" fruits = csv_data.split(",") print(f"List of fruits: {fruits}")List of fruits: ['apple', 'banana', 'cherry']# Joining a list into a string words_to_join = ["Python", "is", "fun"] joined_sentence = " ".join(words_to_join) print(f"Joined sentence: {joined_sentence}")Joined sentence: Python is fun# Joining with another delimiter path_parts = ["C:", "Users", "Username", "Documents"] path = "\\".join(path_parts) print(f"File path: {path}")File path: C:\Users\Username\Documents
Removing extra characters
For cleaning up text from extra spaces or other characters:
Python 3.13text_with_spaces = " Python " # Removing spaces from both ends cleaned = text_with_spaces.strip() print(f"Without spaces: '{cleaned}'")Without spaces: 'Python'left_cleaned = text_with_spaces.lstrip() print(f"Without spaces on the left: '{left_cleaned}'")Without spaces on the left: 'Python 'right_cleaned = text_with_spaces.rstrip() print(f"Without spaces on the right: '{right_cleaned}'")Without spaces on the right: ' Python'# Removing specific characters text_with_dots = "...Python..." without_dots = text_with_dots.strip('.') print(f"Without dots: '{without_dots}'")Without dots: 'Python'
Method chaining
Every string method returns a new string (remember the immutability rule). That means you can call them one after another via . — the result of one is fed straight into the next. This is called method chaining.
For example, normalising user input: strip surrounding whitespace and lowercase it.
In three steps with intermediate variables:
Python 3.13raw_input = " Hello " without_spaces = raw_input.strip() normalized = without_spaces.lower()
As a one-line chain:
Python 3.13raw_input = " Hello " normalized = raw_input.strip().lower() print(f"'{normalized}'")'hello'
Chaining works because strip() returns a new string, on which lower() is then called immediately. It's a common Python pattern: instead of a bucket of intermediate variables, one expressive chain.
String formatting
You often need to insert variable values into text. In modern Python the standard tool for this is the f-string:
Python 3.13name = "Anna" age = 25 # Just add 'f' before the string and put variables inside {} greeting = f"Hi, my name is {name} and I'm {age} years old." print(greeting)Hi, my name is Anna and I'm 25 years old.# Any expression can go inside {} price = 19.99 quantity = 3 total = f"Total: ${price * quantity:.2f}" print(total)Total: $59.97
Besides f-strings there are two other ways to format strings that you'll see in older code: the "...".format(...) method and the "..." % (...) operator. They aren't normally used in new code: f-strings are simpler and faster.
Understanding check
Let's check how well you've understood working with strings:
What will be the result of the following code?
Python 3.13text = "Python" result = text[1:4]
