Golang如何去掉打印输出末尾的百分号
Golang如何去掉打印输出末尾的百分号 以下是我的代码。我想去掉打印行末尾的 % 字符。
package main
import "fmt"
func main() {
var scores = []int {90, 70, 50, 80, 60, 85}
var length = len(scores) // the len function returns the length of scores
for i := 0; i<length; i++ {
fmt.Printf("%d ", scores[i]) // Output: 90 70 50 80 60 85 %
}
}
更多关于Golang如何去掉打印输出末尾的百分号的实战教程也可以访问 https://www.itying.com/category-94-b0.html
谢谢,Norbert。是的,我在Mac上使用zsh。
更多关于Golang如何去掉打印输出末尾的百分号的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
在修复了 "fmt" 周围的引号之后,我在 Playground 上运行它时,输出中没有看到任何百分号字符:Go Playground - The Go Programming Language
不过我知道,如果程序退出时最后打印的字符不是换行符,ZSH 确实会打印一个百分号,其前景色和背景色是互换的,并且后面会跟一个换行符。
由于你没有打印换行符,我推测你正在使用 ZSH。
在Go语言中,fmt.Printf默认不会在输出末尾添加百分号。你看到的百分号很可能是终端或IDE显示的问题,或者是其他原因导致的。你的代码本身是正确的。
以下是几种解决方案:
1. 使用fmt.Print代替fmt.Printf(推荐)
package main
import "fmt"
func main() {
scores := []int{90, 70, 50, 80, 60, 85}
for i := 0; i < len(scores); i++ {
fmt.Print(scores[i], " ")
}
// 输出: 90 70 50 80 60 85
}
2. 使用fmt.Printf但去掉格式字符串中的空格
package main
import "fmt"
func main() {
scores := []int{90, 70, 50, 80, 60, 85}
for i := 0; i < len(scores); i++ {
if i == len(scores)-1 {
fmt.Printf("%d", scores[i]) // 最后一个元素不加空格
} else {
fmt.Printf("%d ", scores[i])
}
}
// 输出: 90 70 50 80 60 85
}
3. 使用strings.Join构建字符串后一次性输出
package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
scores := []int{90, 70, 50, 80, 60, 85}
var strScores []string
for _, score := range scores {
strScores = append(strScores, strconv.Itoa(score))
}
fmt.Print(strings.Join(strScores, " "))
// 输出: 90 70 50 80 60 85
}
4. 使用fmt.Sprint构建输出字符串
package main
import "fmt"
func main() {
scores := []int{90, 70, 50, 80, 60, 85}
output := fmt.Sprint(scores)
fmt.Print(output[1:len(output)-1]) // 去掉切片输出的方括号
// 输出: 90 70 50 80 60 85
}
如果问题仍然存在,可能是你的终端配置问题。可以尝试在打印后添加换行符:
fmt.Printf("%d ", scores[i])
fmt.Println() // 添加换行
或者检查你的终端是否设置了特殊的提示符配置。

