Go (Golang) Tutorial #4 - Printing & Formatting Strings
Summary
TLDRThis tutorial introduces key methods from the fmt package in Go for formatting and printing strings. It explains the difference between Print and Println functions, including how to use escape characters like newline. It then covers Printf, demonstrating how to embed variables within formatted strings using format specifiers. Additionally, it explores saving formatted strings with Sprintf and outputs them for later use. The lesson also showcases working with variables, formatting floats, and determining variable types, with examples that are practical for Go programming learners.
Takeaways
- π¨οΈ The `fmt` package is used to format strings and print them to the console.
- π€ The `fmt.Print` function prints text without adding a new line at the end, unlike `Println`.
- βοΈ To manually add a new line in `Print`, use the escape sequence `\n`.
- π₯ Variables can be printed in strings using multiple arguments separated by commas.
- π‘ `Printf` is used for formatted strings, where variables can be embedded directly into the string using format specifiers.
- π’ The format specifier `%v` outputs the default format of variables in `Printf`.
- π The format specifier `%q` adds quotes around string variables in formatted strings.
- π The format specifier `%T` is used to print the type of a variable in `Printf`.
- π’ To format floats in `Printf`, use `%f` with optional precision control (e.g., `%.2f` for two decimal places).
- πΎ `Sprintf` works like `Printf` but returns the formatted string for later use, instead of printing it directly.
Q & A
What is the purpose of the `fmt` package in Go?
-The `fmt` package in Go is used to format and print strings to the console. It provides various methods like `Print`, `Println`, `Printf`, and `Sprintf` for string formatting and output.
What is the key difference between the `Print` and `Println` functions?
-The key difference is that `Print` does not add a newline at the end of the output, while `Println` automatically adds a newline after printing the content.
How do you manually add a newline in the `Print` function?
-You can manually add a newline in the `Print` function by using the escape sequence `\n` at the desired location in the string.
How can you print multiple values using the `Println` function?
-You can print multiple values using `Println` by separating them with commas inside the parentheses. Each value will be printed with a space separating them.
What is a format specifier in Go, and how is it used in `Printf`?
-A format specifier is a placeholder in a string that is replaced by a value when the string is printed. In `Printf`, it is represented by `%` followed by a letter, like `%v` for the default format of variables.
What does the `%v` format specifier do in `Printf`?
-The `%v` format specifier in `Printf` is the default format for variables and outputs them in their default string representation.
What happens if you use the `%q` format specifier for an integer?
-The `%q` format specifier is intended for strings and will enclose the string in quotes. If used for an integer, it may not work correctly and can produce unexpected output like a hash symbol.
How can you use `Printf` to output the type of a variable in Go?
-You can use the `%T` format specifier in `Printf` to output the type of a variable. For example, `fmt.Printf("%T", age)` would output the type of the `age` variable.
How can you control the number of decimal places when printing a float in Go?
-To control the number of decimal places when printing a float in Go, you can use a format like `%.2f` where the number between `.` and `f` specifies the number of decimal places (e.g., `%.2f` for two decimal places).
What is the difference between `Printf` and `Sprintf` in Go?
-The difference is that `Printf` prints the formatted string directly to the console, while `Sprintf` formats the string and returns it, allowing you to store it in a variable for later use.
Outlines
π₯οΈ Introduction to FMT Package in Go
The speaker introduces the Go package `fmt`, which is used to format and print strings to the console. They explain that the `print` function, unlike `println`, does not automatically add a newline at the end. To create newlines manually, the escape character `\n` is used. The speaker demonstrates this by printing 'Hello' and 'World' without and with newlines, respectively.
π‘ Using Println and Variables in Go
The speaker compares `print` and `println`, showing that `println` automatically adds a newline after printing. They print 'Hello ninjas' and 'Goodbye ninjas' using `println`, showcasing the automatic newlines. The speaker further explains how to print variables using `println` by combining text and variables. They demonstrate this by printing the speaker's age (35) and name (Sean).
π Introduction to Formatted Strings
The speaker introduces formatted strings in Go, which allow embedding variables directly into a string using placeholders called format specifiers. The `printf` function is used to insert variables into a string. The speaker shows how to format variables like age and name using the placeholder `%v` and explains that the order of the variables matters. They also demonstrate using `%q` to enclose strings in quotes and `%t` to print the type of a variable.
π’ Formatting Floating-Point Numbers
The speaker explains how to format floating-point numbers using `%f` to control the number of decimal places. They demonstrate printing a float value and limiting it to a specific number of decimal places, such as one or two. By placing a number between the `%` and `f`, they control the rounding of the float, showing how it rounds up when necessary.
π Using Sprintf to Save Formatted Strings
The final method covered is `sprintf`, which works similarly to `printf`, but instead of printing the formatted string directly to the console, it saves the formatted string into a variable. The speaker shows how to store and print the saved string, emphasizing that `sprintf` is useful when you need to manipulate or use the formatted string later in the program.
Mindmap
Keywords
π‘fmt package
π‘Print function
π‘Println function
π‘Escape sequence
π‘Variables
π‘Formatted strings
π‘Format specifiers
π‘Sprint function
π‘Type formatting
π‘Floating point numbers
Highlights
Introduction to the fmt package used for formatting strings and printing them to the console.
Explaining the difference between fmt.Print and fmt.Println, where Print does not add a newline automatically.
Demonstration of using the escape sequence '\n' to manually add a new line in fmt.Print.
Using variables within fmt.Print and fmt.Println functions by passing them as arguments.
Introduction to formatted strings with fmt.Printf for embedding variables directly into strings using format specifiers.
Explaining the use of format specifier %v, which outputs variables in their default format in fmt.Printf.
Example of using %q to put quotes around strings when outputting with fmt.Printf.
Using %T as a format specifier to output the data type of a variable in fmt.Printf.
Demonstrating how to output float values with fmt.Printf and controlling the number of decimal places.
Explanation of rounding behavior when limiting float outputs to a specific number of decimal places in fmt.Printf.
Introduction to fmt.Sprintf, which is similar to fmt.Printf but stores the formatted string in a variable instead of printing it.
Using fmt.Sprintf to save formatted strings for later use and print them at a different time.
Clarification of the differences between fmt.Print, fmt.Println, fmt.Printf, and fmt.Sprintf in terms of functionality and use cases.
Overview of how format specifiers like %v, %q, %T, and %f are used to format output in different ways.
Final mention of additional format specifiers available in the fmt package and a link provided for further exploration.
Transcripts
all right then gang so in this lesson i
want to talk about this package that we
import right here
fmt and this is used to format strings
and print them out to the console so
we're going to go through a few
different methods that we can use to do
this
now in the past we've already seen one
of these it was the print line function
but i'm going to start with something
slightly different
and that is the print function so we say
fmt
which is the package we import dots
print and it starts with a capital
letter remember
all of these methods are going to start
with a capital letter because they're
made public
from this package now inside here we can
pass in a string so i'm going to say
hello and then a comma and then a space
now the print function right here is a
bit like the print line function that we
saw
the very start of this tutorial series
except for one difference
and that difference is that at the end
of this print
right here when we print it to the
console this doesn't add on a new line
whereas the print line does
and we'll see that in action in a second
i'm going to duplicate this line so we
have two prints and i'm going to change
this string to
world so hello world right so if i
save this now and open up the console
i'm going to clear this to give us a bit
of room
and i'm going to run this file so go run
main dot go and we should see these two
statements printed
to the console down here we see hello
world and they're not
on new lines because like i said print
doesn't add a new line
to the end of the string right here if
we want to do that we have to manually
do it
and to do that we use the escape key
which is a backslash and then
n which stands for new line and we can
see this is a slightly different color
to say it's a special character or an
escaped key
and this will add on a new line a new
carriage return
down here so if i was to add on now
another
print statement let me just duplicate
that and add on
new line right here and we'll add on the
new line as well at the end of this one
if i was to save this now and run the
file again
then we should see this right here new
line on a new line which
we do because of this character right
here okay so that's the print function
all right so next let's look at the
print line again so fmt
dots print line like so
and this again does pretty much the same
thing but it's going to add
this thing automatically at the end
without us having to manually do it
so i could say here hello ninjas like so
and then i'll do another print line and
say goodbye ninjas
and save it let's run this and they
should automatically be on
separate lines and they are so i tend to
use this a little bit more
than this there are special occasions
where i will use this like
getting information from the user in the
console but we'll see that later on
all right then so again i'm going to
clear this console give us a bit of room
and then up here we'll do another
example so what i'm going to do is just
paste in a couple of variables here
because i want to show you that we can
output variables
to the console as well using these print
functions
so i'm going to say fmt dot
print line and then inside parentheses
i'm going to start with a string and say
my age
is and then i'm going to do a comment
after the string and as a second
argument
i'm going to output the age variable so
we can do this we're going to output
several different values to this
function right here
and comma separate them so it's going to
say my age is
and then whatever this age is 35 then a
comma
and then i'll do another string and i
say and my name
is and then outside of the string a
comma and then we'll output the name
variable
so if i save this and run then we should
be able to see
all of that printed to the console my
age is 35 and my name is
sean awesome so that's how we output
variables very simple
okay that so this was print
line and by the way this is how you do
comments in go just the same as
javascript and some other programming
languages
just double forward slash all right so
after that i want to show you how to do
formatted strings which are a little bit
more complicated
so a formatted string is a way to create
a string with variables embedded inside
it so we can do something
like this where we output variables to
the console but instead of having to
break out of the string
then use the variable then back into the
string then out and then use the
variable
instead we can just create one string
and embed the variables inside it
that's what a formatted string is all
about so let me do a comment first
here to say print f that's the function
name and then in parentheses i'm going
to say
formatted strings like so
so how does this work well let's say fnt
then
print f that's the method and then
inside here we pass in a string
now i'm going to say my age is and then
underscore that's where i
later want to output a variable and
my name is underscore again i'm going to
output another variable right here
so i want to output the age here and the
name
right here how do i do that inside a
formatted string well i pass in extra
arguments
and these arguments the variables i want
to output inside the string
and the order matters so we're passing
the age first and then the name
and the way we output these is by using
format specifiers
right here inside the string so a format
specifier starts with
a percentage and then some kind of
character now i'm going to start with
v which is the default format for
variables
so what this does is take a look at this
string first of all and says okay i've
found this percent v
so i'm going to look for the first
variable because this
is the first time i found it in the
string and that's why the order matters
and i'm going to output that right here
i'm going to do the same over here
percent v
meaning output this in the default
format
looks through the string and says this
is the second one i found i'm going to
find the second
value over here and output that in its
default format
right here so let me save this and run
it
go run main go and we should see the
same string as this
this thing right here so we output age
right here
and the name right here okay
so remember this is called a format
specifier and it's how we output
these variables inside a formatted
string and there's loads of different
characters we can use with these
now for now i'm just going to say
percent v
or rather percent underscore to
represent some kind of character
is equal to a format specifier so we
know what that is and this
underscore can be many different letters
right and the different
format specifiers output them in
different ways
and we're going to see a few of them now
so let me duplicate this to do another
example and this time i'm going to
change this to
q and i'm going to change this to q as
well
so what that does is place quotes around
the variables
when we output them now this is not
going to work
on the age because this is an integer
and not a string
and ideally these should be used on
strings so let me save this
and run it and we can see right here
oops we need a new line first of all so
let me add those on because
this doesn't add new lines on
automatically so backslash
and then n on both of those i'm gonna
run this again so we can see it again
and we can see my age is hash and my
name is sean
so this right here hasn't worked it's
just placing a hash instead of the
actual age and this has worked we have
double quotes
around the name variable so that's what
this does
now if we changed age to be the string
age then it's going to work for this
variable as well
and i can demo that i'm going to run
this file again and we can see now
we get 35 in quotes and shown in quotes
all right then so let me change this
back to just a number
35. so let me do another example
i'm going to come down here and say oops
onto the next line
fmt dot print
f and this time i'm going to say age
if i can type is of type
and then i'm going to use percentage t
and what this does
is get us the type of variable
so if i put in here age
like this then it's going to look at the
first variable we pass in
and it's going to output the type of
that variable so
if i save it and run this let me clear
first to give us some room
and run the file then we can see
age is of type int all right
all right there so what about outputting
things like floats
well let's do that i'm going to say fmt
dot print f and then another string
and i'll say you scored then underscore
for now
points like so we need to add on our new
line
characters keep forgetting to do that
okay
so what i want to do is output a float
here now i don't have a float variable
but we can pass the value directly
in here so i could say for example two
two five point five five that is a float
right
now to output a float i could say
percentage
f that stands for float right now if i
save this
and run it we're gonna see that float
but we're gonna see loads of decimal
points over here
so we can limit the number of decimal
points we output
by putting a number between the percent
and the f so if i want it to two decimal
points i could say
not point two if i want it to one i can
say not point one
so let's give this a whirl i'm gonna
save it and run it
and we should see the same thing but
this time it's rounded it to one decimal
point it's rounded up to six here
because five rounds up to six all right
cool so that is formatted
strings there are other characters we
can use here and different format
specifiers
and what i'll do is leave a link down
below to a page with all of these
different format specifiers listed so
you can check them out for yourself
and play around with them alright so the
final method i want to show you
is called sprint f so sprint f
is very much like printf except it saves
the string in a variable for us so we
can do something with it later on
so let me do a comment sprint f so save
printf basically so we can save
formatted strings
and then below that we're going to do an
example so i'm going to say
fmt dot sprint f this time
and then all i'm going to do is pass in
the same thing
as this one right here so let me grab
that
and paste in right here so we're
outputting this string
and then we have the age for this and
the name
for this right so the same example as
above only this time
this is not going to directly print it
out to the console instead it returns
that formatted string
to us and we can store it in a variable
so i could say
var str call it what you want is equal
to fmt dot sprint f
and this returns us that string now if i
hover over this we get an error because
we're not using it
i can print this to the console by
saying fmt
dot print line and then we're going to
output the string
so we'll say the saved string
is colon and then comment and we'll
output str
so if i save this now open up the
console
run this again it should work we can see
the saved
string is and then this is the saved
string returned to us
right here awesome so like i said
there's
many format specifiers we've just seen a
few of them and if you want to check out
more
that link is going to be down below
which shows all of the different format
specifiers
right here so you can browse through
those and play around with some of them
but
we've covered all of the ones that we'll
probably use in
the rest of this tutorial series and if
we cover any more i will explain them
at the time anyway next up we're going
to talk about arrays and slices
5.0 / 5 (0 votes)