简体   繁体   中英

What's the difference between these codes? Why do they have different outputs?

list = ['first', 'second', 'third', 'fourth']
s = '/'
newList = s.join(list)
print(newList)

This code outputs

"first/second/third/fourth"

list = ['first', 'second', 'third', 'fourth']
s = '/'
newList = s.join(str(list))
print(newList)

This code outputs

 "[/'/f/i/r/s/t/'/,/ /'/s/e/c/o/n/d/'/,/ /'/t/h/i/r/d/'/,/ /'/f/o/u/r/t/h/'/]"

What does str() do here that causes the list to separate by every letter?

The str() create a string like "['first', 'second', 'third', 'fourth']" .

And s.join() treat the string as a char array. Then it put '/' between every element in the array.

str converts it's argument to its string representation. The string representation of a list is a single string starting with an opening square bracket and ending with a closing one. The elements in between are converted using repr and separated by , . That string is in itself an iterable of characters. As such, join will place a / between each element of the iterable, ie, between every character of the string.

The equivalent to your first code would be to convert every string element of the list into a separate string:

s.join(str(x) for x in list)

In your particular case, str is a no-op because it will return the argument if the input is already a str .

For arbitrary lists, the approach shown here is better than just using s.join(list) , because join requires all the elements of the iterable to be str s, but makes no attempt to convert them, as say print would. Instead, it raises a TypeError when it encounters a non- str .

Another, less pythonic, but nevertheless very common, way of expressing the same conversion is

s.join(map(str, list))

And of course, the insert the mandatory admonition against naming variables after common builtins here for yourself.

The join function is a string method which returns a string concatentated with the elements of a iterable.

Now, in the first case:

list_1 = ['first', 'second', 'third', 'fourth'] #I changed the name to list_1 as list is a keyword
s = '/'
newList = s.join(list_1)
print(newList)

Every string in the list is a iterable, so, join outputs by concatenating all elements of the list by adding '/' between each element.

In the second case:

list_1 = ['first', 'second', 'third', 'fourth']
s = '/'
newList = s.join(str(list_1))
print(newList)

Since, str converts the entire list including the [ and ] braces as a string. Due to this every character in the new string becomes a iterable and join returns a new string by adding '/' between every element.

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