简体   繁体   中英

“str.split()” method returns “[0]” instead of splitting the string

I am trying to split a string taken from the cmd using os.system but no matter what I split by it always returns [0] .

import os

username = os.system("whoami /user")
username = (str(username).split(' '))

print(username)

For some reason the original output is treated as an integer but that doesn't seem to matter as it is converted to a string.

string = "This is a string"
print(string.split(' '))

This works as intended though!

os.system returns the exit code of the command, not the output. See this question for more detail (and code that does actually get the output). You don't need to run a command to get the username though, just use getpass.getuser() :

import getpass
username = getpass.getuser()

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