【问题标题】:How can I append a number to a string in Racket?如何将数字附加到 Racket 中的字符串?
【发布时间】:2012-01-05 17:09:15
【问题描述】:

Python : xx = "p" + "y" + str(3) => xx == "py3"
如何使用 Racket 获得相同的结果?

(string-append "racket" (number->string 5) " ")  

在 Racket 中是否有另一种方法,类似于上面的 Python 示例,将数字附加到字符串?

【问题讨论】:

  • 你试过你的 Python 例子了吗?
  • 我尝试:TypeError:无法连接 'str' 和 'int' 对象。在这个问题之前,python 自动将数字强制转换为我脑海中的字符串

标签: python racket string-concatenation


【解决方案1】:

Python 会自动将数字强制转换为字符串,而 Racket不会 这样做。 Racket 和 Python 都不会将数字强制转换为字符串。这就是为什么您必须在 Racket 中显式使用 number->string,在 Python 中显式使用 str() ("p" + str(3))。您可能还会发现 Racket 的 format 函数的行为类似于 Python 的 % 运算符的某些用法:

# Python
"py %d %f" % (3, 2.2)

;; Racket
(format "rkt ~a ~a" 3 2.2)

但据我所知,没有与"foo" + 3 等效的 Racket 或 Python

[根据我的错误编辑答案。我将 Python 行为与 JavaScript 混淆了,被 OP 误导]

【讨论】:

  • Python 不会自动将数字强制转换为字符串。 OP 不正确。
【解决方案2】:
$ racket
Welcome to Racket v5.3.5.
-> (~a "abc" "def")
"abcdef"
-> (~a "abc" 'xyz 7 )
"abcxyz7"
-> 

【讨论】:

    猜你喜欢
    • 2012-01-12
    • 2016-03-02
    • 1970-01-01
    • 2012-07-23
    • 1970-01-01
    • 2012-04-14
    • 1970-01-01
    • 2023-01-19
    • 1970-01-01
    相关资源
    最近更新 更多