You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现字符串与数字列表拼接:类似R中paste0的功能

实现类似R中paste0的字符串拼接功能

要给数字列表[0,1,2,3,4,5,6,7,8,9]的每个元素前拼接'foo',你可以用以下几种Python实现方式,效果和R的paste0('foo',0:9)完全一致:

方法1:列表推导式 + f-string(推荐,简洁直观)

nums = [0,1,2,3,4,5,6,7,8,9]
result = [f'foo{num}' for num in nums]

f-string是Python 3.6及以上版本的特性,语法简洁易读,直接在字符串里嵌入变量完成拼接。

方法2:map + lambda 函数

nums = [0,1,2,3,4,5,6,7,8,9]
result = list(map(lambda x: 'foo' + str(x), nums))

map会把列表里的每个数字传给lambda函数,将数字转成字符串后与'foo'拼接,最后用list()把map对象转成列表。

方法3:str.format()(兼容旧版Python)

nums = [0,1,2,3,4,5,6,7,8,9]
result = ['foo{}'.format(num) for num in nums]

如果需要兼容Python 3.5及更早版本,这种方式更稳妥,通过format()方法将数字插入到字符串模板中。

以上三种方法最终都会得到目标结果:['foo0','foo1','foo2','foo3','foo4','foo5','foo6','foo7','foo8','foo9']

内容的提问来源于stack exchange,提问作者therickster

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 10:43:09