想要打印格式设置为典型 fmt 中的行/列表。Printf(“%5s %5s %5s\n”,col1, col2, col3)
如果字符串是纯文本,当然可以正常工作,但如果字符串具有颜色,粗体,字体等显示属性 - 即使可见数据与纯文本的长度相同,并且在%5s中也可以;做 len(col1) 要长得多,它会扭曲表对齐方式。
Printf有没有办法做到这一点,或者另一个std Go包?
要:
Item Item Item
===== ===== ====
abc defgh xyz
x abc d
vv xxxxx zz <=== this happens if string xxxxx has display attributes from
fatih,gchalk, etc. to set foreground/background color
`
//
包装主
import ( “fmt” “github.com/jwalton/gchalk” “github.com/fatih/color” )
func main() {
var colorWithGchalk = gchalk.Red
var data = []string{"one", "ten", "twenty"}
gchalk.SetLevel(gchalk.LevelAnsi16m) // seems needed for gitbash
// note output columns framed by <> just to see actual width
fmt.Println("desired formatted output")
fmt.Printf("<%-10s> <%-10s> <%-10s>\n\n", data[0],data[1],data[2])
/*
** gchalk
*/
// first try using gchalk for color
// colorize second column - column width ignored?
fmt.Println("colorized field loses its 10 character width, so subsequent fields now misaligned")
fmt.Printf("<%-10s> <%-10s> <%-10s>\n", data[0], colorWithGchalk(data[1]), data[2])
// same as above but eliminate gchalk function and just apply colorizing directly - same result
fmt.Printf("<%-10s> <%-10s> <%-10s>\n", data[0], gchalk.Red(data[1]), data[2])
/*
** fatih
*/
fmt.Println("\nwith fatih")
var colorWithFatih = color.New(color.FgRed).SprintFunc()
fmt.Printf("<%-10s> <%-10s> <%-10s>\n", data[0], colorWithFatih(data[1]), data[2])
} `
输出: ' 所需的格式化输出
彩色字段失去其 10 个字符的宽度,因此后续字段现在未对齐
与法提赫
' 在屏幕上,上面的 3 行根据需要以红色显示单词“10”,但字段不再为 10 宽。
牧羊人nacy
小怪兽爱吃肉
慕标琳琳
相关分类