将str_c转换为str_glue

编程语言 2026-07-07

来自以下链接的一个练习题,要求我们:

# Convert the following expressions from str_c() to str_glue()

str_c("\\section{", title, "}")

我以为在 \\section 中的两个反斜杠需要用两个 \\ 来转义,并且要配合花括号 {} 一起考虑这些特殊字符: {", title, "}

我以为答案应该是: -

str_glue("\\\\section{{title}}")

然而,给定的答案是: -

str_glue("\\\\section{{{title}}}")

为什么需要三个括号?

我查看了 https://r4ds.hadley.nz/strings.html,但没有为我解决。

解决方案

让我们来看看 str_c 的输出:

title <- "Chapter 1"

stringr::str_c("\\section{", title, "}")

#> [1] "\\section{Chapter 1}"

正如你所见,我们输出了字面量花括号({)。

关键点是:在 str_glue 中,如果你想要字面打印花括号,需要使用双花括号 {{,如文档所示,文档链接为:文档:

如何在 str_glue() 中使用变量?

将变量名放在模板中的花括号内:str_glue("Hello, {name}") 会插入 name 的值。该变量必须存在于调用环境中,或者你可以将其作为命名参数传入,例如 str_glue("Hello, {name}", name = "Sam")。括号中的任何内容都会作为R 代码运行,因此你也可以调用函数,例如 str_glue("{toupper(name)}")

如何用 str_glue() 打印字面量花括号?

将花括号成对使用。{{ 在输出中产生一个字面量的 {,而 }} 产生一个字面量的 }。例如,str_glue("A set {{1, 2}}") 返回 A set {1, 2}。单独的花括号总是被解释为代码插槽,因此要在最终字符串中将花括号作为文本保留,只有加倍才行。

所以一个花括号只是用来包裹变量名,另外两个是用来打印字面量花括号。

看看下面的输出以了解差异:

title <- "Chapter 1"

stringr::str_c("\\section{", title, "}")
#> [1] "\\section{Chapter 1}"

stringr::str_glue("\\\\section{{{title}}}")
#> \\section{Chapter 1}

stringr::str_glue("\\\\section{title}")
#> \\sectionChapter 1

stringr::str_glue("\\\\section{{title}}")
#> \\section{title}
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章