Course

Python String: Syntax, Usage, and Examples

In Python, a string is a data type that consists of a sequence of characters within single (') or double (") quotes. Strings can include any characters, including letters, numbers, and special characters.

How to Use Python Strings

The syntax of creating a string literal in the Python programming language is simple. Here’s an example:

python
# Single and double quotes create strings print('Hello, World!') print("Hello, World!")

The value of single-quote and double-quote strings is the same. In the example, both calls of the print() function display Hello, World!.

When to Use Python Strings

Python strings are essential for working with text. From handling user input to storing textual data in variables, strings are fundamental to almost every Python program.

Examples of Python Strings

Strings are so common that it’s hard to pick a particular use case for them. Here are some simple examples:

Working with Text

The most basic use of strings is representing text as values or within variables. Python programs of any kind use strings to display, manipulate, or store text.

python
message = "Hello, World!" print(message)

Parsing Configuration Files

Strings are essential for reading configuration files and extracting key-value pairs for application settings.

python
config_line = "max_connections: 10" key, value = config_line.split(": ")

Data Cleaning in Data Science

In data science, strings are fundamental for cleaning and preparing data, such as stripping whitespace or replacing characters.

python
raw_data = " 42, 7.5, 19 " cleaned_data = [float(item.strip()) for item in raw_data.split(",")]

File Paths

Strings are crucial for constructing and modifying file paths across different operating systems.

python
import os base_dir = "/usr/local" sub_dir = "bin" full_path = os.path.join(base_dir, sub_dir)

Learn More About Python Strings

Adding Strings Together

You can combine strings into a single string with the + operator or the join() function. Here’s an example using the + operator to join first_name, " ", and last_name:

python
first_name = "John" last_name = "Doe" full_name = first_name + " " + last_name # Concatenates with a space print(full_name) # Output: John Doe

The join() method allows for more efficient concatenation, especially when dealing with many strings.

python
# Using the .join() method for a list of strings words = ["Hello", "world", "from", "Python"] sentence = " ".join(words) print(sentence) # Output: Hello world from Python

In the example, performing the join() on a space (" ") adds a space between the list items.

String Indexing and Slicing

Like in other sequences, the first item of a string has an index of 0. You can access individual characters or a range of characters in a string through indexing and slicing:

python
first_name = "Joanna" initial = first_name[0] # Accessing the first character print(initial) # Output: J nickname = first_name[0:1] # Slicing from index 0 to 1 print(nickname) # Output: Jo

Escaping Characters in a String

An escape sequence allows you to use special characters in strings that are part of Python syntax or have no direct expression. Many escape sequences involve a backslash (\\) and the special character you want to use within the string.

For example, assume you want to include a double quote within a string. You can either enclose the string in single quotes or escape the double quote with a backslash:

python
print('"No," he confessed') # Output: "No," he confessed print("\"No,\" he confessed") # Output: "No," he confessed

Escaping is also useful for file paths on Windows computers, which generally include backslashes:

python
file_path = "C:\\Users\\Bill\\Documents\\file.txt" print(file_path)

Special escape sequences are available for new lines (\\n) and tabs (\\t), which have no direct expression. For example, to format a multi-line address in a single string, you might use \\n:

python
address = "Währinger Str. 2-4\n1090 Vienna\nAustria" print(address)

Converting to Strings

In Python, the str() method can convert various data types into strings. Using str() is straightforward and works with common data types, including integers, floats, booleans, and even complex objects. The conversion process is simple for basic data types:

python
age = 42 print("Age: " + str(age)) # Output: "Age: 42"

For more complex objects, str() returns a string that represents the object, often the same as the output of print():

python
lottery_numbers = [9, 11, 32, 36, 45, 54] print("Lottery numbers: " + str(lottery_numbers)) # Output: "Lottery numbers: [9, 11, 32, 36, 45, 54]"

Converting from Strings

Python has several built-in functions for converting strings into other data types. For example, int() and float() parse string representations of numbers back into numeric types:

python
string_number = "123" integer_number = int(string_number) float_number = float(string_number) print(integer_number) # Output: 123 (as an integer) print(float_number) # Output: 123.0 (as a float)

Empty Strings

An empty string in Python is a string object that contains no characters. You can create empty strings using single quotes ('') or double quotes ("") without any characters in between. Despite containing no visible characters, empty strings are usable like any other string.

Empty strings are common in comparisons:

python
user_input = input("Enter your name: ") if user_input == '': print("You didn't enter anything, please try again.") else: print(f"Hello, {user_input}!")

Another use case for empty strings is building strings within a loop. Here’s an example:

python
# Start with an empty string favorite_foods = "" # Set a flag for the loop adding_items = True while adding_items: # Ask the user to input a food item or type 'done' to finish food_item = input("Enter a favorite food (or type 'quit' to finish): ") if food_item == 'quit': # Exit the loop adding_items = False else: # Add the food item to the string, followed by a comma and space if favorite_foods: # Checks if favorite_foods is not empty favorite_foods += ", " # Adds a separator before the next item favorite_foods += food_item # Output the final list print("Your favorite foods are: " + favorite_foods)

Python String Formatting with F-Strings

For user-facing messages, strings are often a combination of different values. In Python, f-strings offer a concise and efficient formatting method to embed Python expressions inside strings. To format a string, the syntax using f-string is straightforward. Simply prefix a string with f and use curly braces ({ and }) to include the expressions you want to insert.

Here’s an example of an f-string:

python
name = "Joanna" age = 42 print(f"My name is {name} and I am {age} years old.")

F-strings aren’t just about inserting variables to create formatted string literals. You can also execute functions, perform operations, and use format specifiers:

python
price = 19.99 quantity = 3 print(f"The total price is: {price * quantity}")

Common String Methods

The Python programming language has various built-in methods that allow you to perform common tasks on strings.

  • upper() and lower() methods change the case of the string:
python
regular_string = "Python" print(regular_string.upper()) # Output: PYTHON print(regular_string.lower()) # Output: python
  • strip() removes whitespace from the beginning and end of the string:
python
padded_string = " Python " clean_string = padded_string.strip() print(clean_string) # Output: Python
  • replace() substitutes a substring within the string with another substring:
python
original_string = "Python" new_string = original_string.replace("Python", "JavaScript") print(new_string) # Output: JavaScript
  • find() searches for a substring within the string and returns the starting index of the substring:
python
sentence = "Find the needle in the haystack!" position = sentence.find("needle") print(position) # Output: 9
  • split() divides a string into a list based on a specified separator:
python
data = "Python,HTML,CSS,JavaScript" languages = data.split(",") print(languages) # Output: ['Python', 'HTML', 'CSS', 'JavaScript']