0

Python 3 Two Code Examples, can't understand behaviour of split and format

Hey sololearners, i got a question concerning two code examples. Explanation: I open the URL Apple.com and want to get the header. If I use format, ..., I get the charset. But if I leave "format," as in 2nd Code I get an array. I really don't understand why is the function "format" working in the combination of split. ### 1. Code ### from urllib.request import Request from urllib.request import urlopen myRequest = Request('http://www.apple.com') myResponse = urlopen(myRequest) format, params = myResponse.getheader('Content-Type').split ### End of 1. Code ### ###Output 1. Code### charset=UTF-8 ###End of Output 1. Code### ### 2. Code ### from urllib.request import Request from urllib.request import urlopen myRequest = Request('http://www.apple.com') myResponse = urlopen(myRequest) params = myResponse.getheader('Content-Type').split ### End of 2. Code ### ###Output 2. Code### ['text/html', ' charset=UTF-8'] ###End of Output 2. Code### Thanks for your help.

24th Feb 2017, 12:16 AM
Laszlo
Laszlo - avatar
3 ответов
+ 1
First ask yourself what does myResponse.getheader('Content-Type') return? Probably something like: 'text/html charset=UTF-8' The split method returns a list of all words or character strings that are not seperated by whitespace, using that whitespace as the default delimiter to split them into their respective list elements. So you get: ['text/html', 'charset=UTF-8'] Which is why you see this in Output 2 as the output when using only one variable to put the list in. However if we use more than one variable python is smart enough to put each element into its corresponding variable. If there is not enough variables for each element in the list, the remaining items are placed into the last variable. If there are more variables than there are elements, the remaining variables will be equal to None or null. So for Output 1: format should be 'text/html' params should be 'charset=UTF-8'
24th Feb 2017, 3:40 AM
ChaoticDawg
ChaoticDawg - avatar
0
i think you forget the print in both code1 and code2, then you will understand why
24th Feb 2017, 3:40 AM
Steven Wang
Steven Wang - avatar
0
Hi ChaoticDawg, thanks a lot for your help, I thought format would be somekind of method or function but its a variable. So now I get it. @Huan Wang In my code I used the print method but in the given code I forgot to place it.
26th Feb 2017, 2:49 PM
Laszlo
Laszlo - avatar