与for循环一起使用的字符串join()方法

编程入门 行业动态 更新时间:2024-10-25 02:31:33
本文介绍了与for循环一起使用的字符串join()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要您的帮助,因为我不明白为什么可以将join()方法与for循环作为参数一起使用.

I need your help, because I don't understand why is possible to use the join() method with a forloop as an argument.

例如:

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

Python文档:

str.join(iterable) 返回一个字符串,该字符串是可迭代的字符串的串联.

str.join(iterable) Return a string which is the concatenation of the strings in iterable.

如果可迭代项中有任何非字符串值(包括字节对象),则会引发TypeError.元素之间的分隔符是提供此方法的字符串.

A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method.

可以请人解释吗?

推荐答案

语句(str(x) for x in list)被称为生成器表达式:

>>> (str(x) for x in [1,2,3]) <generator object <genexpr> at 0x7fc916f01d20>

这是创建一个对象,该对象可以被精确地迭代一次,并产生一次可以创建的元素.您可以像列表一样遍历它,如下所示:

What this does is create an object that can be iterated over exactly once, and yields elements that would be created one at a time. You can iterate over it as you would a list, like this:

>>> gen = (str(x) for x in [1,2,3]) >>> for s in gen: ... print s ... 1 2 3

生成器表达式是可迭代的,因此join函数的作用是对其进行迭代并连接其值.

A generator expression is iterable, so what the join function does is iterate over it and join its values.

更多推荐

与for循环一起使用的字符串join()方法

本文发布于:2023-07-09 02:25:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1082889.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   方法   join

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!