Golang可以像Python一样多次使用字符串吗?

时间:2015-10-15 02:52:25

标签: python string python-3.x go

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可以做某事吗?

3 个答案:

答案 0 :(得分:75)

它有一个函数而不是运算符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 2中,len计算普通字符串上的字节数和Unicode字符串上的符文(u'...'):

>>> len('ā') #=> 2
>>> len(u'ā') #=> 1

在Python 3中,普通字符串 Unicode字符串,len计算符文;如果要计算字节数,则必须先将字符串编码为bytearray

>>> len('ā') #=> 1
>>> len(bytearray('ā', encoding='utf-8')) #=> 2

在Go中,只有一种字符串。所以你不必转换,但你必须选择与你想要的语义相匹配的函数。)

答案 1 :(得分:12)

是的,它可以,虽然不是运营商,但在标准库中有功能。

使用简单的循环非常简单,但标准库为您提供了高度优化的版本: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()

答案 2 :(得分:1)

烨。字符串包有一个Repeat function