简体   繁体   中英

What does split('\000') do in this python code?

drives = win32api.GetLogicalDriveStrings()
drives = drives.split('\000')[:-1]

Above is a piece of code from a project I was assigned to. After the first line is executed, the drives variable is the following:

C:\D:\

After the second line is executed, it turns into this:

['C:\\', 'D:\\']

But what does '\000' mean exactly? I've never seen that before.

'\000' is an octal sequence. The intention of the code is obviously to split on NULL.

If the code works as stated in the question then the actual value returned from GetLogicalDriveStrings() is:

"C:\\\000D:\\\000"

Of course, if you print() that, what you'll see is:

C:\D:\

win32api.GetLogicalDriveStrings returns a string of the drives separated by the Null character, code point 0. It can be represented in a string literal with \x00 (hex) or \000 (octal). There is no character/glyph when you print it to your console.

Also, it's not to be confused with the character of the number 0 which is code point 48 (base 10) or 0x30 (hex).

repr returns the representation of the string.

ord returns the Unicode code point of a character.

import win32api

drives = win32api.GetLogicalDriveStrings()
print(repr(drives))
for char in drives:
    print(ord(char), char)

Output:

'C:\\\x00D:\\\x00'
67 C
58 :
92 \
0 
68 D
58 :
92 \
0 

See:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM