← Back to Guides

Degree Symbol in Python: Complete Guide

Master degree symbol (°) usage in Python programming for temperature displays, angle calculations, and scientific applications. This comprehensive guide covers Unicode handling, encoding best practices, library integration, and practical code examples.

Quick Copy

°
\u00B0
chr(176)

Choose the format that works best for your Python code

Python Degree Symbol Usage

5
Implementation Methods
100%
Unicode Compatible
3+
Library Integrations
15+
Code Examples

Methods for Using Degree Symbol in Python

Method 1: Using Unicode Character

Directly use the degree symbol in your Python code. This is the simplest method when your file uses UTF-8 encoding.

# Using the degree symbol directly
temperature = 25.5
print(f"Temperature: {temperature}°C")

# Or using the symbol in a variable
degree_symbol = "°"
angle = 90
print(f"Angle: {angle}{degree_symbol}")

# In function definitions
def format_temp(temp, unit="C"):
    return f"{temp}°{unit}"

print(format_temp(22.5, "C"))

Pros

  • ✓ Most readable in code
  • ✓ Simple to type
  • ✓ No extra functions needed

Cons

  • ⚠ Requires UTF-8 encoding
  • ⚠ May cause issues in older terminals

Output: Temperature: 25.5°C

Output: Angle: 90°

Output: 22.5°C

Method 2: Unicode Escape Sequence

Use the Unicode escape sequence \u00B0 for maximum compatibility across different systems and encodings.

# Using Unicode escape sequence
temperature = 25.5
print(f"Temperature: {temperature}\u00B0C")

# Store as a constant
DEGREE_SYMBOL = "\u00B0"
angle = 45
print(f"Angle: {angle}{DEGREE_SYMBOL}")

# In class definitions
class TemperatureConverter:
    DEGREE = "\u00B0"

    @staticmethod
    def celsius_to_fahrenheit(celsius):
        fahrenheit = celsius * 9/5 + 32
        return f"{celsius}{TemperatureConverter.DEGREE}C = {fahrenheit}{TemperatureConverter.DEGREE}F"

print(TemperatureConverter.celsius_to_fahrenheit(25))

Pros

  • ✓ Works with any encoding
  • ✓ Maximum compatibility
  • ✓ Safe for version control
  • ✓ No terminal issues

Cons

  • • Less readable in source code
  • • Slightly longer to type

Recommended Approach: Use \u00B0 for better encoding compatibility in production code

Method 3: UTF-8 File Encoding

Ensure your Python files use UTF-8 encoding for special characters.

# Add this at the top of your Python file
# -*- coding: utf-8 -*-

# Now you can use degree symbols directly
celsius = 20
fahrenheit = 68
print(f"{celsius}°C = {fahrenheit}°F")

Tip: The encoding declaration should be on the first or second line

Method 4: Using chr() Function

Generate the degree symbol dynamically using Python's built-in chr() function with Unicode code point 176.

# Using chr() function
degree_symbol = chr(176)
temperature = 30
print(f"Temperature: {temperature}{degree_symbol}C")

# Or in a function
def format_temperature(temp, unit="C"):
    return f"{temp}{chr(176)}{unit}"

print(format_temperature(25, "C"))
print(format_temperature(77, "F"))

# Dynamic symbol generation
def get_symbol(name):
    symbols = {
        'degree': 176,
        'celsius': 8451,  # ℃
        'fahrenheit': 8457  # ℉
    }
    return chr(symbols.get(name, 176))

print(f"Water freezes at {get_symbol('celsius')}0{get_symbol('degree')}")

Pros

  • ✓ Dynamic symbol generation
  • ✓ Good for configurable systems
  • ✓ Can generate multiple symbols
  • ✓ Encoding independent

Cons

  • ⚠ Function call overhead
  • ⚠ Less intuitive than constants

Output: Temperature: 30°C

Output: 25°C

Output: 77°F

Output: Water freezes at ℃0°

Method 5: Using Constants

Define constants for consistent symbol usage across your project. This is the recommended approach for large applications.

# Define constants in a separate file (symbols.py)
SYMBOLS = {
    'DEGREE': "\u00B0",
    'CELSIUS': "C",
    'FAHRENHEIT': "F",
    'KELVIN': "K"
}

# Usage functions
def to_celsius(fahrenheit):
    celsius = (fahrenheit - 32) * 5/9
    return f"{celsius:.1f}{SYMBOLS['DEGREE']}{SYMBOLS['CELSIUS']}"

def to_fahrenheit(celsius):
    fahrenheit = celsius * 9/5 + 32
    return f"{fahrenheit:.1f}{SYMBOLS['DEGREE']}{SYMBOLS['FAHRENHEIT']}"

def format_angle(degrees):
    return f"{degrees:.1f}{SYMBOLS['DEGREE']}"

# Temperature class with constants
class Temperature:
    DEGREE = "\u00B0"

    def __init__(self, value, unit="C"):
        self.value = value
        self.unit = unit

    def __str__(self):
        return f"{self.value}{self.DEGREE}{self.unit}"

    def to_celsius(self):
        if self.unit == "F":
            return Temperature((self.value - 32) * 5/9, "C")
        return self

    def to_fahrenheit(self):
        if self.unit == "C":
            return Temperature(self.value * 9/5 + 32, "F")
        return self

# Usage examples
print(to_celsius(68))
print(to_fahrenheit(20))
print(format_angle(45.5))

temp = Temperature(25, "C")
print(f"Current: {temp}")
print(f"In Fahrenheit: {temp.to_fahrenheit()}")

Pros

  • ✓ Consistent across project
  • ✓ Easy to modify globally
  • ✓ Professional approach
  • ✓ Supports internationalization

Cons

  • • Requires setup overhead
  • • More files for simple projects

Output: 20.0°C

Output: 68.0°F

Output: 45.5°

Output: Current: 25°C

Output: In Fahrenheit: 77.0°F

Practical Examples

Temperature Conversion Program

def convert_temperature(value, from_unit, to_unit):
    """Convert temperature between Celsius and Fahrenheit"""
    DEGREE = "\u00B0"

    if from_unit.upper() == "C" and to_unit.upper() == "F":
        result = value * 9/5 + 32
        return f"{result:.1f}{DEGREE}F"
    elif from_unit.upper() == "F" and to_unit.upper() == "C":
        result = (value - 32) * 5/9
        return f"{result:.1f}{DEGREE}C"
    else:
        return f"{value}{DEGREE}{from_unit}"

# Examples
print(convert_temperature(25, "C", "F"))  # 77.0°F
print(convert_temperature(68, "F", "C"))  # 20.0°C

Angle Calculations

import math

def degrees_to_radians(degrees):
    """Convert degrees to radians"""
    return math.radians(degrees)

def radians_to_degrees(radians):
    """Convert radians to degrees"""
    return math.degrees(radians)

def format_angle(degrees):
    """Format angle with degree symbol"""
    return f"{degrees:.1f}\u00B0"

# Examples
angle_deg = 90
angle_rad = degrees_to_radians(angle_deg)
print(f"{angle_deg}\u00B0 = {angle_rad:.4f} radians")

angle_rad = math.pi / 4
angle_deg = radians_to_degrees(angle_rad)
print(f"{angle_rad:.4f} radians = {format_angle(angle_deg)}")

Weather Data Processing

class WeatherData:
    def __init__(self, temperature, humidity, pressure):
        self.temperature = temperature
        self.humidity = humidity
        self.pressure = pressure
        self.DEGREE = "\u00B0"

    def display_celsius(self):
        return f"Temperature: {self.temperature}{self.DEGREE}C"

    def display_fahrenheit(self):
        temp_f = self.temperature * 9/5 + 32
        return f"Temperature: {temp_f:.1f}{self.DEGREE}F"

    def weather_report(self):
        return (f"{self.display_celsius()}\n"
                f"Humidity: {self.humidity}%\n"
                f"Pressure: {self.pressure} hPa")

# Usage
weather = WeatherData(22, 65, 1013)
print(weather.weather_report())

Best Practices

Do's

  • ✓ Use UTF-8 encoding for your Python files
  • ✓ Define constants for frequently used symbols
  • ✓ Use Unicode escape sequences for compatibility
  • ✓ Test symbol display in different environments
  • ✓ Handle encoding errors gracefully

Don'ts

  • ✗ Don't assume all terminals support Unicode
  • ✗ Don't hardcode symbols without encoding declaration
  • ✗ Don't mix different symbol representations
  • ✗ Don't forget to handle file encoding when reading/writing
  • ✗ Don't use images when text symbols work better

Common Issues and Solutions

UnicodeEncodeError

Error when printing degree symbols to console.

# Solution: Use proper encoding
import sys
import io

# Set stdout encoding
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

# Or use environment variables
# export PYTHONIOENCODING=utf-8

File Encoding Issues

Problems reading/writing files with degree symbols.

# Solution: Always specify encoding
with open('data.txt', 'r', encoding='utf-8') as f:
    content = f.read()

with open('output.txt', 'w', encoding='utf-8') as f:
    f.write(f"Temperature: 25\u00B0C")

Web Display Issues

Degree symbols not showing correctly in web applications.

# Solution: Use proper content type
from flask import Flask
app = Flask(__name__)

@app.route('/')
def home():
    return "Temperature: 25\u00B0C", 200, {'Content-Type': 'text/html; charset=utf-8'}

Advanced Features & Techniques

Performance Comparison

Benchmark different methods for performance-critical applications.

import timeit

# Test methods
def method_unicode():
    return f"25{chr(176)}C"

def method_escape():
    return f"25\u00B0C"

def method_chr():
    return f"25{chr(176)}C"

def method_constant():
    DEGREE = "\u00B0"
    return f"25{DEGREE}C"

# Benchmark
methods = [method_unicode, method_escape, method_chr, method_constant]
names = ["Unicode Direct", "Escape Sequence", "chr() Function", "Constant"]

for name, method in zip(names, methods):
    time_taken = timeit.timeit(method, number=100000)
    print(f"{name}: {time_taken:.4f} seconds")

Result: Constants and escape sequences are typically fastest for high-performance applications.

Unicode Degree Variants

Explore different degree-related Unicode characters for specific use cases.

# Different degree symbols
DEGREE_SIGN = "\u00B0"           # ° (Standard degree)
DEGREE_CELSIUS = "\u2103"        # ℃ (Degree Celsius)
DEGREE_FAHRENHEIT = "\u2109"     # ℉ (Degree Fahrenheit)
KELVIN = "\u212A"                 # K (Kelvin symbol)
RING_ABOVE = "\u02DA"            # ˚ (Ring above)
SUPERSCRIPT_ZERO = "\u2070"      # ⁰ (Superscript zero)

def format_temperature_advanced(temp, unit):
    symbols = {
        'C': DEGREE_CELSIUS,
        'F': DEGREE_FAHRENHEIT,
        'K': KELVIN,
        '°C': f"{DEGREE_SIGN}C",
        '°F': f"{DEGREE_SIGN}F"
    }

    if unit in symbols:
        return f"{temp}{symbols[unit]}"
    else:
        return f"{temp}{DEGREE_SIGN}{unit}"

# Examples
print(format_temperature_advanced(25, 'C'))      # 25℃
print(format_temperature_advanced(77, 'F'))      # 77℉
print(format_temperature_advanced(273, 'K'))     # 273K
print(format_temperature_advanced(25, '°C'))     # 25°C
°
\\u00B0
Degree Sign
\\u2103
Degree Celsius
\\u2109
Degree Fahrenheit

Library Integration

Matplotlib Plots

import matplotlib.pyplot as plt
import numpy as np

# Generate data
angles = np.linspace(0, 360, 100)
radians = np.radians(angles)
sine_values = np.sin(radians)

# Create plot with degree symbols
plt.figure(figsize=(10, 6))
plt.plot(angles, sine_values, linewidth=2, color='blue')
plt.xlabel(f'Angle ({chr(176)})', fontsize=12)
plt.ylabel('sin(θ)', fontsize=12)
plt.title('Sine Function Over 360°', fontsize=14, fontweight='bold')
plt.grid(True, alpha=0.3)
plt.xticks(range(0, 361, 45))
plt.axhline(y=0, color='k', linestyle='-', alpha=0.3)
plt.show()

# Temperature plot
temperatures = [20, 25, 30, 35, 40]
humidity = [65, 70, 75, 80, 85]

plt.figure(figsize=(8, 6))
plt.scatter(temperatures, humidity, s=100, c='red', alpha=0.7)
plt.xlabel(f'Temperature ({chr(176)}C)', fontsize=12)
plt.ylabel('Humidity (%)', fontsize=12)
plt.title('Temperature vs Humidity', fontsize=14)
for i, (temp, hum) in enumerate(zip(temperatures, humidity)):
    plt.annotate(f'{temp}{chr(176)}C', (temp, hum),
                 xytext=(5, 5), textcoords='offset points')
plt.grid(True, alpha=0.3)
plt.show()

Pandas DataFrames

import pandas as pd
import numpy as np

# Create DataFrame with temperature data
data = {
    'City': ['New York', 'London', 'Tokyo', 'Paris', 'Sydney'],
    'Temperature (°C)': [22, 18, 25, 20, 28],
    'Temperature (°F)': [72, 64, 77, 68, 82],
    'Humidity (%)': [65, 70, 60, 68, 55],
    'Wind Direction': ['N', 'W', 'E', 'S', 'SE']
}

df = pd.DataFrame(data)
print("Original DataFrame:")
print(df)

# Add formatted temperature column
df['Formatted Temp'] = df['Temperature (°C)'].apply(lambda x: f"{x}{chr(176)}C")

# Create temperature ranges
df['Temp Range'] = pd.cut(df['Temperature (°C)'],
                         bins=[0, 15, 25, 35],
                         labels=['Cold (<15°C)', 'Mild (15-25°C)', 'Hot (>25°C)'])

print("\\nEnhanced DataFrame:")
print(df[['City', 'Formatted Temp', 'Temp Range']])

# Advanced DataFrame operations
def format_temperature_row(row):
    return f"{row['City']}: {row['Temperature (°C)']}{chr(176)}C/{row['Temperature (°F)']}{chr(176)}F"

df['Full Description'] = df.apply(format_temperature_row, axis=1)
print("\\nTemperature Descriptions:")
print(df['Full Description'])

# Export with proper encoding
df.to_csv('weather_data.csv', encoding='utf-8', index=False)
df.to_excel('weather_data.xlsx', index=False)

Tip: Always specify encoding='utf-8' when saving to CSV files with degree symbols.

Tkinter GUI Applications

import tkinter as tk
from tkinter import ttk, messagebox

class TemperatureConverterApp:
    def __init__(self, root):
        self.root = root
        self.root.title("Advanced Temperature Converter")
        self.root.geometry("400x300")

        # Degree symbol constant
        self.DEGREE = chr(176)

        self.setup_ui()

    def setup_ui(self):
        # Main frame
        main_frame = ttk.Frame(self.root, padding="10")
        main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))

        # Title
        title_label = ttk.Label(main_frame, text=f"Temperature Converter {self.DEGREE}",
                               font=("Arial", 14, "bold"))
        title_label.grid(row=0, column=0, columnspan=3, pady=10)

        # Input fields
        ttk.Label(main_frame, text="Celsius:").grid(row=1, column=0, padx=5, pady=5)
        self.celsius_entry = ttk.Entry(main_frame, width=15)
        self.celsius_entry.grid(row=1, column=1, padx=5, pady=5)

        ttk.Label(main_frame, text="Fahrenheit:").grid(row=2, column=0, padx=5, pady=5)
        self.fahrenheit_entry = ttk.Entry(main_frame, width=15)
        self.fahrenheit_entry.grid(row=2, column=1, padx=5, pady=5)

        # Buttons
        button_frame = ttk.Frame(main_frame)
        button_frame.grid(row=3, column=0, columnspan=3, pady=10)

        ttk.Button(button_frame, text="C → F",
                  command=self.celsius_to_fahrenheit).grid(row=0, column=0, padx=5)
        ttk.Button(button_frame, text="F → C",
                  command=self.fahrenheit_to_celsius).grid(row=0, column=1, padx=5)
        ttk.Button(button_frame, text="Clear",
                  command=self.clear_fields).grid(row=0, column=2, padx=5)

        # Result display
        self.result_label = ttk.Label(main_frame, text="", font=("Arial", 11))
        self.result_label.grid(row=4, column=0, columnspan=3, pady=10)

        # Temperature scale
        scale_frame = ttk.LabelFrame(main_frame, text="Temperature Scale", padding="5")
        scale_frame.grid(row=5, column=0, columnspan=3, pady=10, sticky=(tk.W, tk.E))

        self.temp_scale = ttk.Scale(scale_frame, from_=-50, to=150,
                                   orient=tk.HORIZONTAL, length=300)
        self.temp_scale.grid(row=0, column=0, padx=5, pady=5)

        self.scale_label = ttk.Label(scale_frame, text=f"20{self.DEGREE}C")
        self.scale_label.grid(row=0, column=1, padx=5)

        self.temp_scale.set(20)
        self.temp_scale.bind("", self.update_scale_label)

    def celsius_to_fahrenheit(self):
        try:
            celsius = float(self.celsius_entry.get())
            fahrenheit = celsius * 9/5 + 32
            self.fahrenheit_entry.delete(0, tk.END)
            self.fahrenheit_entry.insert(0, f"{fahrenheit:.1f}")
            self.show_result(celsius, "C", fahrenheit, "F")
        except ValueError:
            messagebox.showerror("Error", "Please enter a valid number for Celsius")

    def fahrenheit_to_celsius(self):
        try:
            fahrenheit = float(self.fahrenheit_entry.get())
            celsius = (fahrenheit - 32) * 5/9
            self.celsius_entry.delete(0, tk.END)
            self.celsius_entry.insert(0, f"{celsius:.1f}")
            self.show_result(fahrenheit, "F", celsius, "C")
        except ValueError:
            messagebox.showerror("Error", "Please enter a valid number for Fahrenheit")

    def show_result(self, from_temp, from_unit, to_temp, to_unit):
        result_text = f"{from_temp:.1f}{self.DEGREE}{from_unit} = {to_temp:.1f}{self.DEGREE}{to_unit}"
        self.result_label.config(text=result_text)

    def clear_fields(self):
        self.celsius_entry.delete(0, tk.END)
        self.fahrenheit_entry.delete(0, tk.END)
        self.result_label.config(text="")

    def update_scale_label(self, event):
        temp = self.temp_scale.get()
        fahrenheit = temp * 9/5 + 32
        self.scale_label.config(text=f"{temp:.0f}{self.DEGREE}C / {fahrenheit:.0f}{self.DEGREE}F")

# Create and run the application
if __name__ == "__main__":
    root = tk.Tk()
    app = TemperatureConverterApp(root)
    root.mainloop()

Features: Interactive temperature converter with scale, validation, and real-time updates.

Additional Libraries

# Flask Web Application
from flask import Flask, render_template_string

app = Flask(__name__)

@app.route('/')
def temperature_converter():
    template = """
    

Temperature Converter {{ degree_symbol }}

""" return render_template_string(template, degree_symbol=chr(176)) # NumPy Scientific Computing import numpy as np def temperature_analysis(temps_celsius): """Analyze temperature data with degree symbols""" temps_fahrenheit = temps_celsius * 9/5 + 32 mean_c = np.mean(temps_celsius) mean_f = np.mean(temps_fahrenheit) return { 'data': { 'celsius': [f"{t}{chr(176)}C" for t in temps_celsius], 'fahrenheit': [f"{t}{chr(176)}F" for t in temps_fahrenheit] }, 'statistics': { 'mean_celsius': f"{mean_c:.1f}{chr(176)}C", 'mean_fahrenheit': f"{mean_f:.1f}{chr(176)}F" } } # Example usage temperatures = np.array([20, 22, 25, 28, 30]) analysis = temperature_analysis(temperatures) print(f"Mean Temperature: {analysis['statistics']['mean_celsius']}") # Jupyter Notebook Display from IPython.display import display, Markdown def display_temperature_table(data): """Display formatted temperature table in Jupyter""" headers = "| City | Temperature | Humidity |" separator = "|------|-------------|----------|" rows = [] for item in data: rows.append(f"| {item['city']} | {item['temp']}{chr(176)}{item['unit']} | {item['humidity']}% |") table = "\\n".join([headers, separator] + rows) display(Markdown(table)) # Example data weather_data = [ {'city': 'New York', 'temp': 22, 'unit': 'C', 'humidity': 65}, {'city': 'London', 'temp': 18, 'unit': 'C', 'humidity': 70}, {'city': 'Tokyo', 'temp': 25, 'unit': 'C', 'humidity': 60} ] # Use in Jupyter: display_temperature_table(weather_data)

Frequently Asked Questions

Interactive Python Demo

Try Python Code Online

Test these degree symbol examples directly in your browser:

Quick Temperature Converter

# Temperature conversion with degree symbols
def celsius_to_fahrenheit(celsius):
    fahrenheit = celsius * 9/5 + 32
    return f"{celsius}{chr(176)}C = {fahrenheit:.1f}{chr(176)}F"

# Test conversions
for temp in [0, 20, 37, 100]:
    print(celsius_to_fahrenheit(temp))

Performance Test

Related Guides

Key Takeaways

Best Practices

  • Use UTF-8 encoding for all Python files
  • Prefer Unicode escape sequences (\u00B0) for compatibility
  • Define constants for consistent usage across projects
  • Always specify encoding in file operations

Implementation Tips

  • Test symbols display in different environments
  • Handle encoding errors gracefully
  • Use appropriate Unicode variants for specific contexts
  • Consider performance for critical applications

Ready to master degree symbols in Python?

Start with the Unicode escape sequence method and build your expertise from there.