我们如何在string.join()中使用自定义迭代?

时间:2018-05-30 17:29:15

标签: python string python-3.x join string-operations

srings的join()方法似乎适用于list字符串和其他内置迭代。但是,当我定义自己的迭代时,join()合作。如何编写join()很乐意拥有的迭代?

class IterATOR: # iter-ATOR
    def __init__(self):
        self.x = 0
    def __next__(self):
        self.x += 1
        if self.x > 4:
            raise StopIteration()
        return 'hello world'

class IterABLE: # iter-ABLE
    def __iter__(self):
        return IterATOR()


print(30 * '#', 'BEGIN TEST ONE', 30 * '#')
gable = IterABLE()
gator = iter(gable)
try:
    while True:
        print(next(gator))
except StopIteration as exc:
    print(exc)


print(30 * '#', 'BEGIN TEST TWO', 30 * '#')
gable = IterABLE()
for elem in gable:
    print(elem)


print(30 * '#', 'BEGIN TEST THREE', 30 * '#')

lyst = [str(x) for x in range(0, 5)]
# tcs: test cases
tcs = [lyst, IterABLE(), iter(IterABLE()), IterATOR(), lyst, iter(lyst)]

for tc in tcs: # for test case in test cases:
    try:
         print(type(tc).__name__.ljust(20), end ='')
         merged_str = ''.join(tc)
         print(" was a success:".ljust(20), repr(merged_str))
    except Exception as exc:
        print(" was a failure:".ljust(20), str(exc))

测试三的输出是:

############################## BEGIN TEST THREE ##############################
list                 was a success:      '01234'
IterABLE             was a failure:      'IterATOR' object is not iterable
IterATOR             was a failure:      can only join an iterable
IterATOR             was a failure:      can only join an iterable
list                 was a success:      '01234'
list_iterator        was a success:      '01234'

0 个答案:

没有答案