Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pretty formatting of string variable with multiple "\n"

Tags:

string

go

I am having some issues formatting string variables with multiple \n (carriage returns) in it. I have a string variable that has stored in it the following:

"1. Check the connections \n2. Have the firewall settings been checked \n3. Check switch/network connections \n4. Contact admin"

Now, I want to print the line so that it looks like this:

Remedy:                  1.  Check the connections
                         2.  Have the firewall setting been checked
                         3.  Check switch/network connections
                         4.  Contact admin

However, in my program when I run the output line:

fmt.Println("remedy:\t\t\t\t" + alt.Remedy)

It comes up like this:

remedy:                         1. Check the connections
2. Have the firewall settings been checked
3. Check switch/network connections
4. Contact admin

How do I get it so that by issuing that command, all 4 options are listed in the same column? In this example, I want options 2, 3, and 4 listed under the #1 option.

like image 664
jberthia Avatar asked Jan 26 '26 16:01

jberthia


1 Answers

The Go Programming Language Specification

String literals

A string literal represents a string constant obtained from concatenating a sequence of characters. There are two forms: raw string literals and interpreted string literals.

Raw string literals are character sequences between back quotes, as in foo. Within the quotes, any character may appear except back quote. The value of a raw string literal is the string composed of the uninterpreted (implicitly UTF-8-encoded) characters between the quotes; in particular, backslashes have no special meaning and the string may contain newlines. Carriage return characters ('\r') inside raw string literals are discarded from the raw string value.


Use a raw string literal. For example,

package main

import (
    "fmt"
)

func main() {
    message := `
Remedy:                  1.  Check the connections
                         2.  Have the firewall setting been checked
                         3.  Check switch/network connections
                         4.  Contact admin
`

    fmt.Print(message[1:])
}

Playground: https://play.golang.org/p/pdgAoYnBIch

Output:

Remedy:                  1.  Check the connections
                         2.  Have the firewall setting been checked
                         3.  Check switch/network connections
                         4.  Contact admin
like image 57
peterSO Avatar answered Jan 28 '26 07:01

peterSO



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!