Home > database >  Why is 'arg' a list inside the function but returned as a string?
Why is 'arg' a list inside the function but returned as a string?

Time:01-13

def strip_split(arg):
    arg = arg.split(", ")
    return arg


users = ["admin, adm1n"]

for user in users:
    strip_split(user)
    print(user)
    print(user[0])

This is a very simple program but I can't work out why arg is a list inside the function (I've tested using print(arg)), but when 'arg' is returned it comes out as a string.

I expected that when I 'print(user)' the output is '["admin, adm1n"]' and 'print(user[0])' is 'admin', however I get 'admin, adm1n' and 'a'.

CodePudding user response:

You're not setting user to the result of the function:

def strip_split(arg):
    arg = arg.split(", ")
    return arg


users = ["admin, adm1n"]

for user in users:
    user = strip_split(user)
    print(user)
    print(user[0])

Gives your expected results as you're assigned the value back. Strings are immutable so you can't change them as such, just assign new values.

CodePudding user response:

Actually strip_split(user) is doing "admin, adm1n".split(", ") which gives ['admin', 'adm1n']. But, you are not assigning it to user or any other variable.

So it is giving this output:

for user in users:
    print(user)

#'admin, adm1n'

If you want the result you have to assign it to a variable or itself:

for user in users:
    user = strip_split(user)
    print(user)
    print(user[0])

#output
['admin', 'adm1n']
admin
  • Related