Python中的join()函数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_18149897/article/details/81092075
author.qq = ''.join(
            str(random.choice(range(10))) for _ in range(9)  //随机生成用户的QQ号
        )

在这个代码片中,我们可以看到.join()函数可以用来将字符串进行拼接,令我疑惑的是在首次随机选取数字并str之后应该进行join函数操作,但是函数执行的结果却是完成for循环之后再join.



qq = ''.join(
            str(random.choice(range(10))) for _ in range(9)
        )
print(qq)
177291006                  //可见


print(''.join(123))           //可以看到参数需要设置为迭代器对象
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: can only join an iterable
print(''.join(range(4)))
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: sequence item 0: expected str instance, int found

关键是.join()函数接收iterable对象并在之后进行函数操作

猜你喜欢

转载自blog.csdn.net/qq_18149897/article/details/81092075