Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

go - print without space between items

Tags:

go

fmt.Println("a","b")

I want to print the two strings without space padding, namely "ab", but the above will print "a b".

Go fmt

Do I just switch to using Printf ?

fmt.Printf("%s%s\n","a","b")
like image 675
null Avatar asked Sep 19 '14 07:09

null


People also ask

How do you print a variable without spaces between values?

To print multiple values or variables without the default single space character in between, use the print() function with the optional separator keyword argument sep and set it to the empty string '' .

How do you remove spaces when printing in Python?

Method 1: By using strip() method The split() function basically removes the leading and the trailing spaces of the string. Key points: strip(): This function removes the leading and the trailing spaces from an array including the tabs(\t). lstrip(): This function removes spaces from the left end of the string.


3 Answers

Plain old print will work if you make the last element "\n".
It will also be easier to read if you aren't used to printf style formatting.

See here on play

fmt.Println("a","b")
fmt.Print("a","b","\n")
fmt.Printf("%s%s\n","a","b")

will print:

a b
ab
ab
like image 117
David Budworth Avatar answered Nov 01 '22 09:11

David Budworth


As it can be found in the doc:

Println formats using the default formats for its operands and writes to standard output. Spaces are always added between operands and a newline is appended. It returns the number of bytes written and any write error encountered.

So you either need to do what you already said or you can concatenate the strings before printing:

fmt.Println("a"+"b")

Depending on your usecase you can use strings.Join(myStrings, "") for that purpose.

like image 41
Mateusz Dymczyk Avatar answered Nov 01 '22 08:11

Mateusz Dymczyk


Println relies on doPrint(args, true, true), where first argument is addspace and second is addnewline. So Prinln ith multiple arguments will always print space.

It seems there is no call of doPrint(args, false, true) which is what you want. Printf may be a solution, Print also but you should add a newline.

like image 1
GHugo Avatar answered Nov 01 '22 09:11

GHugo