想要打印格式設置為典型 fmt 中的行/列表。Printf(“%5s %5s %5s\n”,col1, col2, col3)如果字符串是純文本,當然可以正常工作,但如果字符串具有顏色,粗體,字體等顯示屬性 - 即使可見數據與純文本的長度相同,并且在%5s中也可以;做 len(col1) 要長得多,它會扭曲表對齊方式。Printf有沒有辦法做到這一點,或者另一個std Go包?要:Item Item Item===== ===== ====abc defgh xyzx abc dvv 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.Redvar data = []string{"one", "ten", "twenty"}gchalk.SetLevel(gchalk.LevelAnsi16m) // seems needed for gitbash// note output columns framed by <> just to see actual widthfmt.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 resultfmt.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 寬。
3 回答

牧羊人nacy
TA貢獻1862條經驗 獲得超7個贊
Printf有沒有辦法做到這一點,
不
還是另一個標準 Go 包?
不
(你所謂的“顯示屬性”是字節輸出流的一部分,它們不是“屬性”,這是終端仿真器解釋的“內聯數據”。您可以做的是在打印之前過濾掉此內聯數據。

慕標琳琳
TA貢獻1830條經驗 獲得超9個贊
在Jason Walton的建議下,Chalk to gchalk的搬運工。我得到了fmt。Printf %s 以滿足我的需求,盡管如果字段寬度(%s)較窄,它們可能會出現問題。
我想將至少兩個字符串連接在一起以提供一個%s。第一個字符串是純文本(sgCharToPrint),下一個字符串是彩色的,所以它是實際的屏幕文本(missedRaw)(錯過的是顏色字符串,例如missueRaw用ansi格式字符包裝。
myLen = len(sgCharToPrint) + len(missedRaw)
填充 = sgCharToPrint + missed + 字符串。重復(“ ”, 30 - olen)
騰訊網.Printf(“%30s %4d %10s \n”,填充,值,尾部)
現在,“表”顯示保持對齊狀態。
- 3 回答
- 0 關注
- 107 瀏覽