Golang 可以像 Python 那样乘以字符串吗?
技术问答
527 人阅读
|
0 人回复
|
2023-09-11
|
Python 可以这样串乘字符:# d1 F* K" H z5 d
Python 3.4.3 (default,Mar 26 2015年22:03:40[GCC 4.9.2] on linuxType "help","copyright","credits" or "license" for more information.>>> x = 'my new text is this long'>>> y = '#' * len(x)>>> y'########################'>>>& x: |& i6 Q2 r- k7 K3 R8 i# p
Golang 能以某种方式做同样的事吗?7 q/ W, ~$ i4 v) }% [
2 Y; |' s, r5 a- `
解决方案: " P( ?2 c' o( a/ _ p7 }
它有一个函数是运算符,strings.Repeat。这是您的 Python 示例端口,您可以在这里操作:; P, ^, o; {1 o$ ] ]* l
package mainimport "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)}
* d0 I" v1 T$ K( V3 d; S* S0 E 请注意,我用了utf8.RuneCountInString(x)而不是len(x); 前者计算符文(Unicode 代码点),后者计算字节。"my new text is this long",差异并不重要,因为所有的字符都只有一个字节,但养成指定你意思的习惯是很好的:
% P/ {% x0 K: [len("ā") //=> 2utf8.RuneCountInString("ā") //=> 1
4 k3 r; ]* T8 d+ M* s 因为这是 Python 比较问题,请注意 Python 中,one 函数len根据您调用的内容计算不同的内容。Python 2 中,纯字符串上的字节数和 Unicode 字符串上的符文 ( u'...'):% [. ~3 t3 i7 c- L
Python 2.7.18 (default,Aug 15 2020年17:03:20>>> len('ā') #=> 2>>> len(u'ā') #=> 16 S3 `% G- C) F( O
而在现代 Python 中,纯字符串是Unicode 字符串:
- A1 }9 z- D( z" P% A8 YPython 3.9.6 (default,Jun 29 2021,19:36:19>>> len('ā') #=> 1# c s3 J* z3 J0 X! D( f! j U- D9 h
要计算字节数,需要计算字节数bytearray先将字符串编码成一个:) `+ E b; P6 P" ^! O B Z
>>> len('ā'.encode('UTF-8')) #=> 2, B5 \. [$ q7 U5 H2 L" G
所以Python为了获得它们的长度,有多种类型的字符串和函数;Go 只有一个字符串,但你必须选择与你想要的语义相匹配的长度函数。 |
|
|
|
|
|