String vs Byte String
एक String Characters का Sequence होता है; ये एक Abstract Concept हैं और इन्हें Directly Disk पर Store नहीं किया जा सकता। एक Byte String Bytes का Sequence होती है - ऐसी चीजें जो Disk पर Store की जा सकती हैं। इनके बीच Mapping को Encoding कहते हैं - इनमें से काफी सारे हैं (और अनंत संभव हैं) - और Conversion करने के लिए आपको पता होना चाहिए कि Particular Case में कौन सा Apply होता है, क्योंकि Different Encoding Same Bytes को Different String में Map कर सकती है।
उदाहरण: Same Bytes, Different Strings
>>> b'\xcf\x84o\xcf\x81\xce\xbdo\xcf\x82'.decode('utf-16')
'蓏콯캁澽苏'
>>> b'\xcf\x84o\xcf\x81\xce\xbdo\xcf\x82'.decode('utf-8')
'τορνoς'
एक बार जब आप जान जाते हैं कि किस Encoding का उपयोग करना है, तो आप Byte String की .decode() Method का उपयोग करके उससे सही Character String प्राप्त कर सकते हैं। Character String की .encode() Method Opposite Way जाती है और Character String को Byte String के रूप में Encode करती है।
Key Differences:
| Aspect | String (str) | Byte String (bytes) |
|---|---|---|
| Content | Unicode Characters | Raw Bytes (0-255) |
| Mutable | No | No (bytearray का उपयोग करें) |
| Literal Syntax | 'hello' या "hello" | b'hello' |
| Encoding | N/A (Already Decoded) | Required to Decode |
| Use Case | Text Processing | I/O, Network, Files |
Conversion:
# String to Bytes (Encode)
text = "Hello, 世界"
bytes_utf8 = text.encode('utf-8')
bytes_utf16 = text.encode('utf-16')
# Bytes to String (Decode)
text_back = bytes_utf8.decode('utf-8')
# Error Handling
text.decode('utf-8', errors='ignore') # Invalid Bytes Skip करें
text.decode('utf-8', errors='replace') # से Replace करें
text.decode('utf-8', errors='strict') # Default - Raise Error