Search code examples
pythonlistreturn

Python: Why does returning a string change it to a list (of length one)


I'm creating a string in a method and returning it. But I get back a list in stead of a string.

def method():
    string1 = "hallo1 \nhallo2"
    print("string1 :")
    print(type(string1))
    print(string1)
    return[string1]    

string2=method()
print("string2 :")
print(type(string2))
print(string2)

I would suspect both string1 and string2 to be of type string and be identical, in stead I get the following output:

string1 :
<class 'str'>
hallo1
hallo2
string2 :
<class 'list'>
['hallo1 \nhallo2']

Suspected/wanted output:

string1 :
<class 'str'>
hallo1
hallo2
string2 :
<class 'str'>
hallo1
hallo2

I do have experience with code, but I haven't been in school for 10 years, and haven't coded much since, also I have no real Python experience, so I could well be I'm missing something simple/stupid.

My google skills left me with nothing here, so I'm hoping someone here can shed some light on what is happening.


Solution

  • As mentioned in the comments you wrote in code return [string1]
    This instructs python to return a list with a single element string1 as the return value from method.

    Accordingly its type is list and not string if you had put a second item in the list, the print out would differ more drastically to highlight this difference.