Search code examples
pythonstringprintingcasting

Unexpected behavior when casting from list to string on Python


I was messing around with Python when I found this behavior I can't really make sense of it. Code is the following:

x = ['A','B','C','D']
x = str(x)
y = "ABCD"

print(f"x = {x} \nx.find('B') is: {x.find('B')}\n\n")
print(f"y = {x} \ny.find('B') is: {y.find('B')}\n\n")

print(x)
print(y)

print(type(x)==type(y))

and the output on the console is:

x = ['A', 'B', 'C', 'D']
x.find('B') is: 7


y = ['A', 'B', 'C', 'D']
y.find('B') is: 1


['A', 'B', 'C', 'D']
ABCD
True

Things I don't fully understand are: Why x and y are showed as lists when printed in a formatted string?

Why when using simply print(x) or print(y) the ways of printing are different, even though type(x) == type(y)?

And specially why x.find('B') is 7, when the length of the string/list is 4, while y.find('B') works as expected?

Probably a trivial question but I didn't find something similar on the site. Thanks!


Solution

  • The reason your print(y) output looks weird is because you're actually passing x to print. As well, what you're seeing with x.find('B') is happening because you're converting 'x' to a str. This doesn't give you a list, but instead a string that looks like "['A', 'B', 'C', 'D']". So here B really is the 7th index of the string