【问题标题】:How to avoid linebreak in R's sprintf("very very long string with line break")?如何避免 R sprintf 中的换行符(“非常长的带有换行符的字符串”)?
【发布时间】:2015-01-19 05:31:08
【问题描述】:

sprintf() 中有一个很长的字符串。它是如此之长以至于打破它会很有用(可读性)(但仅在源代码中,而不是在输出中)。但是每当我打破长字符串时,它就会引入一个\n,因此输出也有一个换行符。我怎样才能打破源代码中的字符串,使其不会在输出中被打破?

【问题讨论】:

  • 这行得通吗? sprintf('%s%s%s', 'this is a going to be a very long sentence ', 'much longer than the 80 character limit on my terminal ', 'window.')
  • 您好,感谢您的帮助。我的问题不是sprintf 的第二个参数的长度,而是第一个:而不是你的 '%s%s%s',我有一个延伸 80 个字符的字符串,这就是我想打破它的原因。
  • @MariusHofert - 你能显示你的确切sprintf代码的剪辑版本吗?
  • @rawr...好吧,你的想法让我朝着正确的方向前进。我只是使用了cat(sprintf("short string", ...), sprintf("short string", ...)) 形式的构造,所以我基本上有两个较短的sprintf() 字符串/调用。
  • 如果字符串太长而无法在源代码中读取,那么输出中的字符串是否也可能太长?当然,您的脚本被用于它们的输出,而不是它们的源......

标签: r printf


【解决方案1】:

也许像下面这样的东西会很有用(尽管如果不知道输入字符串的实际样子或打算如何使用它们,就很难判断)。

Fmt <- c(" %s is %d feet tall.\n", 
         "%s likes chocolate.\n",
         "%s eats %d bars of chocolate", 
         "every night after dinner.")

sprintf(paste(Fmt, collapse = " "), "Sven", 7, "Sven", "He", 3)
# [1] " Sven is 7 feet tall.\n Sven likes chocolate.\n He eats 3 bars of chocolate every night after dinner."
cat(.Last.value)
#  Sven is 7 feet tall.
#  Sven likes chocolate.
#  He eats 3 bars of chocolate every night after dinner.

【讨论】:

    【解决方案2】:

    使用gsub() 执行相关替换,例如,用单个空格替换连续出现 2 次或更多次的“空格”字符(包括换行符)

    > sprintf("string: %s", gsub("[[:space:]]{2,}", " ", "a very
    +   long
    +   string"))
    [1] "string: a very long string"
    

    【讨论】:

      【解决方案3】:

      使用@Martin 给出的概念,但方式略有不同。

      > sprintf(gsub("[[:space:]]{2,}"," ","
      +         %s is %d feet tall.
      +              %s likes chocolate.
      +              %s eats %d bars of chocolate 
      +              every night after dinner."), "Sven", 7, "Sven", "He", 3)
      [1] " Sven is 7 feet tall. Sven likes chocolate. He eats 3 bars of chocolate every night after dinner."
      > 
      

      【讨论】:

        猜你喜欢
        • 2010-09-19
        • 1970-01-01
        • 2019-11-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-08
        • 2021-07-19
        • 2012-12-27
        相关资源
        最近更新 更多