gpt4 book ai didi

string - 为字符串中的元素分配不同的值

转载 作者:行者123 更新时间:2023-12-04 13:08:48 27 4
gpt4 key购买 nike

我正在使用 R。
假设我有一个城市向量,我想单独使用这些城市名称
在一个字符串中。

city = c("Dallas", "Houston", "El Paso", "Waco")

phrase = c("Hey {city}, what's the meaning of life?")

所以我想以四个单独的短语结束。
"Hey Dallas, what's the meaning of life?"
"Hey Houston, what's the meaning of life?"
...

是否有类似于 Python 中的 format() 的函数可以允许
我以简单/有效的方式执行此任务?

想避免类似下面的事情。
for( i in city){
phrase = c("Hey ", i, "what's the meaning of life?")
}

最佳答案

怎么样sprintf ?

> city = c("Dallas", "Houston", "El Paso", "Waco")
> phrase = c("Hey %s, what's the meaning of life?")
> sprintf(phrase, city)
[1] "Hey Dallas, what's the meaning of life?" "Hey Houston, what's the meaning of life?"
[3] "Hey El Paso, what's the meaning of life?" "Hey Waco, what's the meaning of life?"

关于string - 为字符串中的元素分配不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6458554/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com