普通网友 2015-10-15 02:52
浏览 388
已采纳

Golang可以像Python一样乘以字符串吗?

Python can multiply strings like so:

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
'########################'
>>>

Can Golang do the equivalent somehow?

  • 写回答

3条回答 默认 最新

  • dongmeng0317 2015-10-15 02:54
    关注

    It has a function instead of an operator, strings.Repeat. Here's a port of your Python example, which you can run 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)
    }
    

    Note that I've used utf8.RuneCountInString(x) instead of len(x); the former counts "runes" (Unicode code points), while the latter counts bytes. In the case of "my new text is this long", the difference doesn't matter since all the characters are only one byte, but it's good to get into the habit of specifying what you mean:

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

    (In Python 2, len counts bytes on plain strings and runes on Unicode strings (u'...'):

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

    In Python 3, plain strings are Unicode strings and len counts runes; if you want to count bytes, you have to encode the string into a bytearray first:

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

    In Go, there's only one kind of string. So you don't have to convert, but you do have to pick the function that matches the semantics you want.)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如何用数码管显示学号(相关搜索:单片机)
  • ¥15 错误于library(org.Hs.eg.db): 不存在叫‘org.Hs.eg.db’这个名称的程序包,如何解决?
  • ¥60 求一个图片处理程序,要求将图像大小跟现实生活中的大小按比例联系起来的
  • ¥50 求一位精通京东相关开发的专家
  • ¥100 求懂行的大ge给小di解答下!
  • ¥15 pcl运行在qt msvc2019环境运行效率低于visual studio 2019
  • ¥15 MAUI,Zxing扫码,华为手机没反应。可提高悬赏
  • ¥15 python运行报错 ModuleNotFoundError: No module named 'torch'
  • ¥100 华为手机私有App后台保活
  • ¥15 sqlserver中加密的密码字段查询问题