简体   繁体   English

为什么在反转python中的字符串时为什么要使用join()函数

[英]Why should we use join() function while reversing a string in python

what is the purpose of ''.join() here ''.join()的目的是什么

print(''.join(reversed(a)))

can't we reverse a string only with reversed function 我们不能只使用反向功能来反向字符串吗

print(reversed("python"))

No, you can't do it simply by calling reversed . 不,您不能简单地通过调用reversed来做到这一点。 reversed returns an special reversed iterator object, something that needs to be iterated through in order to produce it's elements. reversed返回一个特殊的reversed迭代器对象,需要对其进行迭代才能生成其元素。

Not supplying it to .join here will just print out the confusing repr of the reversed object: <reversed object at 0x7f2ba02be320> . 不在此处将其提供给.join只会打印出reversed对象的令人困惑的repr<reversed object at 0x7f2ba02be320>

Calling "".join , which takes an iterable as an argument, consumes the reversed object and joins the elements producing the string you see. 调用"".join ,它将一个可迭代的作为参数,将消耗reversed对象,并连接产生您所看到的字符串的元素。

Take note that there's other ways to consume it without join that result in a different object, list , for example, will take the reversed object and create a list out of the elements it produces: 请注意,还有其他不用join就可以使用它的方法,这会导致一个不同的对象,例如list ,它将采用reversed对象并从它产生的元素中创建一个列表:

a = reversed('abcd')
print(list(a))
['d', 'c', 'b', 'a']

If you need a string in the end, then the best option is .join . 如果最后需要一个字符串,那么最好的选择是.join

You can manipulate str same as list : 您可以像list一样操作str

a = 'abcd'
a[::-1] #'dcba'

The purpose of join is to take an iterable and join it by a delimiter to produce a string: join的目的是采用一个可迭代的对象,并通过一个定界符将其连接以产生一个字符串:

''.join(reversed(a))

a can be an iterable that supports the iteration protocol or an object that overloads __getitem__ . a可以是支持迭代协议的可迭代对象,也可以是重载__getitem__的对象。 That is, any object that you would normally want to use in a for loop or comprehension or you would like to iterate on to produce its result and make them as a string, that object could possibly be a potential value for join . 也就是说,您通常希望在for循环或理解中使用的任何对象,或者想要对其进行迭代以产生其结果并将其制成字符串的对象,则该对象可能是join的潜在值。

reversed returns an object that you need to iterate on in order to fetch its values in join . reversed返回一个对象,您需要对其进行迭代才能在join获取其值。 so ''.join(reversed(a)) means the following: reverse a first and then iterate on the resulting object of reversed and join each extracted object by delimiter specified by join , in your case it's just an empty string. 所以''.join(reversed(a))以下装置:扭转a第一,然后将所得的物体上迭代reversed和通过指定的分隔符加入每个提取的对象join ,在你的情况下,它只是一个空字符串。

can't we reverse a string only with reversed function? 我们不能仅使用反向功能来反向字符串吗?

Not really! 并不是的! You can reverse a string using this expression instead of reversed function: 'stackoverflow'[::-1] . 您可以使用此表达式而不是reversed函数来反转字符串: 'stackoverflow'[::-1] As usual, there could be several ways to achieve the same effects in programming. 与往常一样,在编程中可能有几种方法可以达到相同的效果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM