Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将字符串连接到字符串列表的每个元素?_Python_String_Python 3.x_List Comprehension - Fatal编程技术网

Python 如何将字符串连接到字符串列表的每个元素?

Python 如何将字符串连接到字符串列表的每个元素?,python,string,python-3.x,list-comprehension,Python,String,Python 3.x,List Comprehension,我有以下清单: sentence = ['doc1','doc2','doc3','doc4'] 如何在语句的每个元素末尾连接.txt?(*): 我试着列出理解: '.txt '.join(sentence[:-1]) 尽管如此,它还是返回了以下内容: 'doc1.txt doc2.txt doc3' 这是错误的,因为它不同于(*)您没有尝试将整个字符串连接在一起,只需将.txt添加到每个字符串: >>> [s + '.txt' for s in sentence] ['

我有以下清单:

sentence = ['doc1','doc2','doc3','doc4']
如何在
语句
的每个元素末尾连接
.txt
?(*):

我试着列出理解:

'.txt '.join(sentence[:-1])
尽管如此,它还是返回了以下内容:

'doc1.txt doc2.txt doc3'

这是错误的,因为它不同于(*)

您没有尝试将整个字符串连接在一起,只需将
.txt
添加到每个字符串:

>>> [s + '.txt' for s in sentence]
['doc1.txt', 'doc2.txt', 'doc3.txt', 'doc4.txt']

不确定为什么要切掉最后一个元素。

您没有尝试将整个字符串连接在一起,只需将
.txt
添加到每个字符串:

>>> [s + '.txt' for s in sentence]
['doc1.txt', 'doc2.txt', 'doc3.txt', 'doc4.txt']
不确定为什么要切掉最后一个元素。

另一种方法:

>>> sentence = ['doc1','doc2','doc3','doc4']
>>> list(map(lambda x : x + '.txt', sentence))
['doc1.txt', 'doc2.txt', 'doc3.txt', 'doc4.txt']
另一种方法:

>>> sentence = ['doc1','doc2','doc3','doc4']
>>> list(map(lambda x : x + '.txt', sentence))
['doc1.txt', 'doc2.txt', 'doc3.txt', 'doc4.txt']

您可以使用map和lambda

map(lambda x:x+'.txt', sentence)
输出:

['doc1.txt', 'doc2.txt', 'doc3.txt', 'doc4.txt']

您可以使用map和lambda

map(lambda x:x+'.txt', sentence)
输出:

['doc1.txt', 'doc2.txt', 'doc3.txt', 'doc4.txt']

我懂了。。。谢谢你帮我澄清这个问题。我明白了。。。谢谢你帮我澄清这个问题。