Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

python - 为什么是string.join(list)而不是list.join(string)?(Why is it string.join(list) instead of list.join(string)?)

This has always confused me.

(这一直使我感到困惑。)

It seems like this would be nicer:

(看起来这样会更好:)

my_list = ["Hello", "world"]
print(my_list.join("-"))
# Produce: "Hello-world"

Than this:

(比这个:)

my_list = ["Hello", "world"]
print("-".join(my_list))
# Produce: "Hello-world"

Is there a specific reason it is like this?

(是否有特定原因?)

  ask by Evan Fosmark translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It's because any iterable can be joined, not just lists, but the result and the "joiner" are always strings.

(这是因为任何iterable都可以联接,不仅是列表,而且结果和“ joiner”始终是字符串。)

For example:

(例如:)

import urllib2
print('
############
'.join(
    urllib2.urlopen('http://data.stackexchange.com/users/7095')))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...