【问题标题】:Can Golang multiply strings like Python can?Golang 可以像 Python 那样将字符串相乘吗?
【发布时间】:2016-01-13 08:23:30
【问题描述】:

Python 可以像这样将字符串相乘:

Python 3.4.3 (default, Mar 26 2015, 22:03:40)
[GCC 4.9.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> x = 'my new text is this long'
>>> y = '#' * len(x)
>>> y
'########################'
>>>

Golang 能以某种方式做到这一点吗?

【问题讨论】:

    标签: python string python-3.x go


    【解决方案1】:

    它有一个函数而不是一个运算符,strings.Repeat。这是您的 Python 示例的一个端口,您可以运行 here

    package main
    
    import (
        "fmt"
        "strings"
        "unicode/utf8"
    )
    
    func main() {
        x := "my new text is this long"
        y := strings.Repeat("#", utf8.RuneCountInString(x))
        fmt.Println(x)
        fmt.Println(y)
    }
    

    请注意,我使用的是utf8.RuneCountInString(x) 而不是len(x);前者计算“符文”(Unicode 代码点),而后者计算字节。在"my new text is this long" 的情况下,区别并不重要,因为所有字符都只有一个字节,但最好养成指定含义的习惯:

    len("ā") //=> 2
    utf8.RuneCountInString("ā") //=> 1
    

    由于这是一个 Python 比较问题,请注意,在 Python 中,len 的一个函数会根据您调用它的方式计算不同的事物。在 Python 2 中,它计算纯字符串上的字节数和 Unicode 字符串上的符文 (u'...'):

    Python 2.7.18 (default, Aug 15 2020, 17:03:20)
    >>> len('ā') #=> 2
    >>> len(u'ā') #=> 1
    

    而在现代 Python 中,纯字符串 Unicode 字符串:

    Python 3.9.6 (default, Jun 29 2021, 19:36:19) 
    >>> len('ā') #=> 1
    

    如果要统计字节数,需要先将字符串编码成bytearray

    >>> len('ā'.encode('UTF-8')) #=> 2
    

    所以 Python 有多种类型的字符串和一个函数来获取它们的长度; Go 只有一种字符串,但你必须选择与你想要的语义相匹配的长度函数。

    【讨论】:

    • 符文长度与字节长度区分的奖励积分。
    • 优秀而简洁的解释。
    【解决方案2】:

    是的,它可以,虽然不是使用运算符,而是使用标准库中的函数。

    使用简单的循环很容易,但标准库为您提供了一个高度优化的版本:strings.Repeat()

    你的例子:

    x := "my new text is this long"
    y := strings.Repeat("#", len(x))
    fmt.Println(y)
    

    Go Playground 上试试。

    注意:len(x) 是字符串的“字节”长度(字节数)(在 UTF-8 编码中,这是 Go 在内存中存储字符串的方式)。如果您想要字符数(符文),请使用utf8.RuneCountInString()

    【讨论】:

      【解决方案3】:

      是的。字符串包有一个Repeat function

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-09
        • 1970-01-01
        • 1970-01-01
        • 2021-10-17
        相关资源
        最近更新 更多