Common application scenarios of ASCII in programming:
1. Character Validation:
python# Check if character is a letter def is_letter(char): return 'A' <= char <= 'Z' or 'a' <= char <= 'z' # Check if character is a digit def is_digit(char): return '0' <= char <= '9' # Check if character is printable def is_printable(char): return 32 <= ord(char) <= 126
2. Character Conversion:
python# Case conversion def to_upper(char): if 'a' <= char <= 'z': return chr(ord(char) - 32) return char def to_lower(char): if 'A' <= char <= 'Z': return chr(ord(char) + 32) return char
3. String Processing:
python# Remove whitespace characters def trim_whitespace(s): return s.strip() # Remove space(32), tab(9), newline(10/13), etc. # Count character types def count_chars(s): letters = digits = others = 0 for c in s: if 'A' <= c <= 'Z' or 'a' <= c <= 'z': letters += 1 elif '0' <= c <= '9': digits += 1 else: others += 1 return letters, digits, others
4. Data Encoding:
python# Base64 encoding (based on ASCII) import base64 encoded = base64.b64encode(b'Hello').decode('ascii') # URL encoding from urllib.parse import quote encoded = quote('Hello World', safe='')
5. Network Protocols:
- HTTP headers use ASCII encoding
- SMTP, FTP and other protocols are based on ASCII
- JSON strings use ASCII characters
6. File Processing:
python# Read ASCII text file with open('file.txt', 'r', encoding='ascii') as f: content = f.read()
Important Notes:
- Use Unicode when handling non-ASCII characters
- Pay attention to line ending differences (CRLF vs LF)
- Validate input character validity