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

Time:08-05

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.

CodePudding user response:

'\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:\

CodePudding user response:

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:

  • Related