How to print the degree symbol in Python
Learn how to print the degree symbol in Python. Discover various methods, real-world applications, and tips for debugging common errors.

Python developers often need to print the degree symbol (°) for scientific or geographic data. The language offers several straightforward methods to display this special character in your output.
In this guide, you'll explore several techniques to print the degree symbol. You will find practical tips, see real-world applications, and get debugging advice to select the right method.
Using the \u00B0 Unicode escape sequence
temperature = 25
print(f"The temperature is {temperature}\u00B0C")--OUTPUT--The temperature is 25°C
The most direct way to print the degree symbol is by using its Unicode escape sequence, \u00B0. Python recognizes this sequence within strings and automatically converts it to the corresponding character. This method is highly reliable because it’s based on the universal Unicode standard, ensuring your code behaves consistently across different platforms and environments.
In the example, the f-string embeds the temperature variable and then appends the degree symbol using \u00B0 followed by "C". This approach keeps your code clean and readable without needing to import any special libraries.
Basic methods for printing the degree symbol
Beyond the standard Unicode escape sequence, Python provides several other straightforward options for adding the degree symbol to your strings.
Inserting the degree symbol directly in strings
temperature = 30
print(f"The temperature is {temperature}°C")--OUTPUT--The temperature is 30°C
You can also insert the degree symbol ° directly into your string, just as you would any other character. This approach is often the most intuitive, as you can simply copy and paste the symbol or type it using your operating system’s character map. It keeps your code looking clean and straightforward.
- This method relies on your source file being saved with UTF-8 encoding, which is the default for Python 3 and most modern code editors.
- It enhances readability since the final output is visible directly in the code.
Using the chr() function with ASCII code
temperature = 22
degree_symbol = chr(176) # ASCII code for degree symbol
print(f"The temperature is {temperature}{degree_symbol}C")--OUTPUT--The temperature is 22°C
Python's built-in chr() function offers a programmatic way to generate characters from their numeric codes. It takes an integer and returns the corresponding string character. For the degree symbol, the ASCII and Unicode value is 176.
- This approach is especially useful when you're working with character codes dynamically or prefer using numeric values over special characters in your source code.
- The example assigns the output of
chr(176)to thedegree_symbolvariable, making the finalprint()statement more readable and self-explanatory.
Working with named Unicode characters
import unicodedata
temperature = 28
degree_symbol = unicodedata.lookup("DEGREE SIGN")
print(f"The temperature is {temperature}{degree_symbol}C")--OUTPUT--The temperature is 28°C
For a more descriptive approach, you can use Python's unicodedata module. This module provides access to the Unicode Character Database, which contains properties for all Unicode characters. The unicodedata.lookup() function lets you find a character by its official name, making your code more explicit.
- By passing
"DEGREE SIGN"to thelookup()function, you retrieve the corresponding symbol. - This method is self-documenting, improving readability for anyone who might not know the specific Unicode or ASCII code for the symbol.
Advanced techniques for working with the degree symbol
Moving beyond simple print statements, you can build more robust solutions by creating reusable functions and classes to manage temperature formatting and encoding challenges.
Creating a temperature formatting function
def format_temp(value, scale='C'):
return f"{value}°{scale}"
temps = [22, 25, 30]
formatted_temps = [format_temp(t) for t in temps]
print(formatted_temps)--OUTPUT--['22°C', '25°C', '30°C']
Encapsulating formatting logic in a function like format_temp promotes code reuse and consistency. This function accepts a value and an optional scale argument, which defaults to 'C', making it flexible for different temperature units. It then returns a clean, formatted string with the degree symbol.
- This method centralizes your formatting logic, so you only need to make changes in one place.
- The example uses a list comprehension to efficiently apply the function across multiple temperature values in a single line.
Supporting different encodings with the degree symbol
utf8_degree = '\u00B0'.encode('utf-8')
latin1_degree = '\u00B0'.encode('latin-1')
print(f"UTF-8: {utf8_degree}, Latin-1: {latin1_degree}")
print(f"Decoded: {utf8_degree.decode('utf-8')}, {latin1_degree.decode('latin-1')}")--OUTPUT--UTF-8: b'\xc2\xb0', Latin-1: b'\xb0'
Decoded: °, °
When you're working with data that will be written to files or sent over a network, you need to handle character encoding. The encode() method converts a string into a sequence of bytes, which is how computers store and transmit text. Different encodings can represent the same character using different byte patterns.
- The example demonstrates this by encoding the degree symbol into both UTF-8 (
b'\xc2\xb0') and Latin-1 (b'\xb0'). - Using the corresponding
decode()method correctly converts these bytes back into the original symbol, which is crucial for avoiding data corruption when reading or writing text.
Creating a temperature conversion class with proper symbol display
class Temperature:
def __init__(self, value, scale='C'):
self.value = value
self.scale = scale
def __str__(self):
return f"{self.value}°{self.scale}"
temps = [Temperature(0), Temperature(32, 'F'), Temperature(100)]
for temp in temps:
print(temp)--OUTPUT--0°C
32°F
100°C
Creating a Temperature class is a powerful, object-oriented way to handle temperature data. It neatly bundles the numeric value and its scale (like 'C' or 'F') into a single, reusable object. This approach keeps your code clean and intuitive, especially when you're working with multiple temperature readings.
- The
__init__method sets up each new object, assigning thevalueandscale. - The
__str__method provides a user-friendly string representation. When youprint()aTemperatureobject, Python automatically calls this method to display the formatted output, complete with the degree symbol.
Move faster with Replit
Replit is an AI-powered development platform that comes with all Python dependencies pre-installed, so you can skip setup and start coding instantly. This lets you move from learning individual techniques, like using chr(176) or building a Temperature class, to creating complete applications with Agent 4.
Instead of piecing together functions, you can describe the app you want to build and Agent will take it from idea to a working product. For example, you could build:
- A weather dashboard that pulls from a live API and displays temperatures correctly formatted with the degree symbol.
- A scientific calculator for web browsers that handles trigonometric functions and displays angles in degrees.
- A cooking conversion utility that converts oven temperatures between Celsius and Fahrenheit, showing the
°Cor°Fsymbols.
Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.
Common errors and challenges
Even with straightforward methods, you might run into a few common issues when printing the degree symbol, but they're all easily fixed.
Fixing TypeError when combining degree symbols with numerical variables
A TypeError often pops up when you try to combine a number directly with a string, like the degree symbol. Python doesn't allow you to add a string to an integer or float with the + operator. To fix this, you need to convert the number to a string first. The easiest way is using an f-string, which handles the conversion automatically. Alternatively, you can explicitly convert the number using the str() function before concatenating it.
Fixing inconsistent degree symbol display across platforms
If the degree symbol shows up as a strange character or a question mark, you're likely facing an encoding mismatch. Your code might be producing UTF-8 characters, but your terminal or the file you're writing to expects a different encoding.
- Ensure your Python script is saved with UTF-8 encoding, which is the standard for most modern editors.
- When writing to files, specify the encoding—usually UTF-8—to ensure the symbol is saved correctly.
- Check your terminal or console settings to make sure they are configured to display UTF-8 characters correctly.
Correcting KeyError when looking up the degree symbol name
When using the unicodedata module, a KeyError means the name you passed to the lookup() function wasn't found. This is almost always due to a typo. The official name for the degree symbol is "DEGREE SIGN". If you misspell it, for example, as "DEGREE" or "DEGREE_SIGN", Python won't find it in the Unicode database and will raise a KeyError. Double-checking the official character name is the quickest fix.
Fixing TypeError when combining degree symbols with numerical variables
One of the most common roadblocks is the TypeError. This error occurs when you attempt to concatenate a number with a string using the + operator, as Python can't add two different data types. The following code demonstrates this common mistake.
temperature = 25
degree_symbol = '°'
print("The temperature is " + temperature + degree_symbol + "C")
Here, the + operator tries to add a number (temperature) to text, which Python doesn't permit. This mismatch causes the error. See the corrected version below for a simple fix.
temperature = 25
degree_symbol = '°'
print("The temperature is " + str(temperature) + degree_symbol + "C")
The fix is simple: you must convert the number to a string before joining it with other text. By wrapping the temperature variable in str(), you’re telling Python to treat it as text. This allows the + operator to concatenate all the pieces into a single, complete string. You'll often run into this error when manually building strings that include numerical data, so it's a good habit to ensure all parts are strings first.
Fixing inconsistent degree symbol display across platforms
When the degree symbol appears as a garbled character like , it's not your code's fault—it's an encoding mismatch. This happens when the system running the code can't display the character correctly. The simple code below can trigger this exact issue.
temperature = 25
print(f"The temperature is {temperature}°C")
The code produces a character using UTF-8, a modern standard. However, if the terminal or file where you're displaying it uses an older encoding, it won't recognize the symbol. See the corrected version below for a simple fix.
temperature = 25
print(f"The temperature is {temperature}\u00B0C")
The fix replaces the direct symbol with its Unicode escape sequence, \u00B0. This method is more robust because it explicitly tells Python which character to use, bypassing potential encoding conflicts between your editor and the terminal. You're no longer relying on the system to correctly interpret a character from your source file. This is especially important when your code needs to run reliably across different operating systems or environments where default encodings might vary.
Correcting KeyError when looking up the degree symbol name
A KeyError from the unicodedata module is a common hiccup when finding a character by name. This error means the name you gave to the unicodedata.lookup() function doesn't exist in the database, usually due to a typo. The code below shows how this happens.
import unicodedata
temperature = 28
degree_symbol = unicodedata.lookup("DEGREE")
print(f"The temperature is {temperature}{degree_symbol}C")
The unicodedata.lookup() function fails because it needs the character's exact official name. The string "DEGREE" is incomplete, so the function can't find a match in the database. The corrected code below shows the required name.
import unicodedata
temperature = 28
degree_symbol = unicodedata.lookup("DEGREE SIGN")
print(f"The temperature is {temperature}{degree_symbol}C")
The fix is to provide the unicodedata.lookup() function with the character's exact official name. The function requires a precise match, so a partial name like "DEGREE" won't work. You must use the full name, "DEGREE SIGN", to retrieve the symbol correctly. This error is a simple reminder to be precise when working with named constants or lookups, as even a small typo will cause your code to fail.
Real-world applications
Beyond just fixing errors, these techniques are the building blocks for practical applications that handle temperature data professionally.
Creating a simple weather dashboard with degree symbols
By storing temperature data in a dictionary and using an f-string to format the output, you can quickly create a clean, readable weather report that includes the degree symbol.
temperatures = {"New York": 22, "London": 15, "Tokyo": 28, "Sydney": 30}
print("=== CURRENT TEMPERATURES ===")
for city, temp in temperatures.items():
print(f"{city:10}: {temp}°C")
# Find the hottest and coldest cities
hottest = max(temperatures, key=temperatures.get)
coldest = min(temperatures, key=temperatures.get)
print(f"\nHottest: {hottest} ({temperatures[hottest]}°C)")
print(f"Coldest: {coldest} ({temperatures[coldest]}°C)")
This example uses a dictionary to pair cities with their temperatures. It iterates through the dictionary with .items(), printing each city and its temperature in a formatted line. The f-string format specifier {city:10} ensures the city names are neatly aligned in a 10-character space.
To find the hottest and coldest cities, the code uses the max() and min() functions. By setting key=temperatures.get, you tell Python to compare the dictionary's values—the temperatures—instead of its keys, making it easy to identify extremes in the data.
Building a temperature conversion table with proper formatting
A reusable function that handles the conversion logic makes it straightforward to generate a neatly formatted table for comparing temperatures across different scales.
def convert_temp(value, from_scale, to_scale):
if from_scale == 'F':
celsius = (value - 32) * 5/9
elif from_scale == 'K':
celsius = value - 273.15
else:
celsius = value
if to_scale == 'F':
return (celsius * 9/5) + 32
elif to_scale == 'K':
return celsius + 273.15
return celsius
celsius_values = [0, 25, 50, 75, 100]
print("Temperature Conversion Table")
print("---------------------------")
print("°C °F K")
for c in celsius_values:
f = convert_temp(c, 'C', 'F')
k = convert_temp(c, 'C', 'K')
print(f"{c:3.0f} {f:3.0f} {k:3.0f}")
The convert_temp function simplifies temperature conversions by using Celsius as a universal intermediate step. It first converts any input from Fahrenheit or Kelvin into Celsius, then converts that Celsius value to the final target scale. This two-step process keeps the logic straightforward.
- The script then loops through a list of Celsius values, calling the function to get the Fahrenheit and Kelvin equivalents for each.
- It uses an f-string with format specifiers like
{c:3.0f}to print a neatly aligned table, displaying the numbers as whole integers without any decimal points.
Get started with Replit
Now, turn these techniques into a real tool. Describe what you want to build to Replit Agent, like “a web app that converts Celsius to Fahrenheit” or “a weather dashboard that displays live temperatures.”
Replit Agent will write the code, test for errors, and deploy your application for you. Start building with Replit.
Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.
Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.



