diff --git a/Day 1 Homework - Karen.md b/Day 1 Homework - Karen.md index d073fbd..5e5d2f5 100644 --- a/Day 1 Homework - Karen.md +++ b/Day 1 Homework - Karen.md @@ -118,5 +118,34 @@ read_tomato_sales("tomato_sales_error.csv") ``` **10. Given today's conversation about character encodings, describe why you would want to use bytes instead of strings when processing data containing multiple human languages at the same time. Write a small Python function to demonstrate this.** +As being discussed above regarding the three main differences between python strings and bytes, the initial reason I will use bytes instead of strings for process data containing multiple human languages is that bytes allow more flexibility and mutability of handling multilingual texts. Besides numerical values, bytes also can encode text data in different character sets without any potential loss of information, such as UTF-8 and UTF-16. For example, we can defer an encoding and decoding process of text data to see how it can be used in different language situations. +``` +def encode_text(text, encoding='utf-8'): + encoded_text = text.encode(encoding) + return encoded_text +def decode_text(encoded_text, encoding='utf-8'): + decoded_text = encoded_text.decode(encoding) + return decoded_text +``` +Well, I do say it is amazing as the whole encoding process is seamless and suppose my computer will help me to do it (thanks to it). To assume we work in a multiple languages environment and we review yesterday's conversation about Nemawashi, the encoding process allows us to translate different languages into binary data using UTF-8 and people in different language can easily decoding it to be the textual data more efficiently without any loss of information (such loss of information may be caused by the different system used by different people, I usually meet this kind of issues when using emojis and enter any language items that others' computer may not be applicable to read it). +```ruby +def encode_text(text, encoding='utf-8'): + encoded_text = text.encode(encoding) + return encoded_text +def decode_text(encoded_text, encoding='utf-8'): + decoded_text = encoded_text.decode(encoding) + return decoded_text + +text = "Nemawashi, 事先疏通,ねまわし" +encoded_text = encode_text(text, 'utf-16') +print(encoded_text) + +decoded_text = decode_text(encoded_text, 'utf-16') +print(decoded_text) + +#The results are shown as +#b'\xff\xfeN\x00e\x00m\x00a\x00w\x00a\x00s\x00h\x00i\x00,\x00 \x00\x8bNHQ\x8fu\x1a\x90\x0c\xffm0~0\x8f0W0' +Nemawashi, 事先疏通,ねまわし +```