Python Strings: Syntax, Usage, and Examples
How to Use Python Strings
print('Hello, World!')
print("Hello, World!")
When to Use Python Strings
Examples of Python Strings
Working with Text
print(message)
Parsing Configuration Files
key, value = config_line.split(": ")
cleaned_data = [float(item.strip()) for item in raw_data.split(",")]
base_dir = "/usr/local"
sub_dir = "bin"
full_path = os.path.join(base_dir, sub_dir)
Learn More About Python Strings
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:
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.
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.
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:
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
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:
Escaping is also useful for file paths on Windows computers, which generally include backslashes:
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:
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:
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():
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:
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:
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:
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:
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:
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:
print(regular_string.upper()) # Output: PYTHON print(regular_string.lower()) # Output: python
clean_string = padded_string.strip()
print(clean_string) # Output: Python
new_string = original_string.replace("Python", "JavaScript") print(new_string) # Output: JavaScript
position = sentence.find("needle")
print(position) # Output: 9
languages = data.split(",")
print(languages) # Output: ['Python', 'HTML', 'CSS', 'JavaScript']
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.