【问题标题】:Assigning different values to an element in a string为字符串中的元素分配不同的值
【发布时间】:2011-09-21 11:03:53
【问题描述】:

我正在使用 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?")
}

【问题讨论】:

    标签: string r


    【解决方案1】:

    根据需要的复杂程度,一个简单的粘贴就可以完成这项工作:

    paste("Hey ", city, ", what's the meaning of life", sep="")
    

    做你想做的。

    @Zach 的回答,sprintf 有很多优点,比如双打的正确格式等。

    【讨论】:

      【解决方案2】:

      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?"   
      

      【讨论】:

      • 没有 printf,但你可以用printf <- function(format_string, ...) {cat(sprintf(format_string, ...))}滚动自己的
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-16
      • 1970-01-01
      • 2020-05-05
      • 1970-01-01
      • 2021-09-07
      • 1970-01-01
      相关资源
      最近更新 更多