Go (Golang) Tutorial #4 - Printing & Formatting Strings

Net Ninja
21 May 202112:25

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

00:00

🖥️ 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.

05:00

💡 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).

10:01

🔄 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

The 'fmt' package is a core Go (Golang) package used for formatted I/O operations such as printing strings or variables to the console. In the video, the fmt package is used to introduce various methods like 'Print' and 'Println' for displaying text and variables. This package is essential for handling output formatting in Go programs.

💡Print function

The 'Print' function is used in Go to output text to the console without automatically adding a newline at the end. The script explains that unlike 'Println', this function requires manual insertion of a newline (via '\n') to move the cursor to a new line. It’s demonstrated with the example of printing 'hello' and 'world' on the same line.

💡Println function

The 'Println' function in Go prints text followed by an automatic newline character, moving the output to the next line after each call. This function is compared to 'Print', as it simplifies line breaks without requiring escape sequences. In the video, it's used to print phrases like 'hello ninjas' and 'goodbye ninjas' on separate lines.

💡Escape sequence

An escape sequence allows special characters to be included in strings, such as '\n' for a newline. In the video, the presenter uses '\n' to manually add new lines when using the 'Print' function in Go. Escape sequences are important in programming for formatting output.

💡Variables

Variables store data values in programming. In the video, variables like 'age' and 'name' are used to demonstrate how to print dynamic content using 'fmt' methods. Variables are printed alongside strings, showcasing how Go functions can handle and format different types of data.

💡Formatted strings

Formatted strings allow variables to be embedded directly into strings using special format specifiers. In the video, 'Printf' and 'Sprintf' are demonstrated to show how to create strings with placeholders, such as '%v' for variables, which can be filled dynamically. This technique streamlines output formatting.

💡Format specifiers

Format specifiers define how variables should be formatted when embedded into a string. Examples in the video include '%v' for default variable formatting and '%q' for quoting strings. These specifiers are crucial for controlling the appearance of data in formatted output.

💡Sprint function

The 'Sprint' function in Go is used to format a string and store it in a variable instead of immediately printing it to the console. The video shows how 'Sprintf' can save formatted strings for later use, which can then be printed with 'Println'. This function is useful for formatting strings without outputting them right away.

💡Type formatting

Type formatting in Go allows programmers to print the data type of a variable using the '%T' specifier. The video shows how to display the type of the 'age' variable, which is output as 'int'. This feature helps in debugging and understanding variable types during development.

💡Floating point numbers

Floating point numbers are numbers with decimal points, like 225.55. The video explains how to format floating point numbers using '%f' and control the number of decimal places displayed by specifying the precision, such as '%.2f'. This is important when working with precise calculations or displaying 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

play00:02

all right then gang so in this lesson i

play00:04

want to talk about this package that we

play00:05

import right here

play00:06

fmt and this is used to format strings

play00:09

and print them out to the console so

play00:11

we're going to go through a few

play00:12

different methods that we can use to do

play00:14

this

play00:14

now in the past we've already seen one

play00:16

of these it was the print line function

play00:18

but i'm going to start with something

play00:19

slightly different

play00:20

and that is the print function so we say

play00:23

fmt

play00:24

which is the package we import dots

play00:26

print and it starts with a capital

play00:28

letter remember

play00:29

all of these methods are going to start

play00:30

with a capital letter because they're

play00:32

made public

play00:32

from this package now inside here we can

play00:35

pass in a string so i'm going to say

play00:37

hello and then a comma and then a space

play00:39

now the print function right here is a

play00:41

bit like the print line function that we

play00:43

saw

play00:44

the very start of this tutorial series

play00:47

except for one difference

play00:48

and that difference is that at the end

play00:50

of this print

play00:52

right here when we print it to the

play00:53

console this doesn't add on a new line

play00:56

whereas the print line does

play00:58

and we'll see that in action in a second

play01:00

i'm going to duplicate this line so we

play01:01

have two prints and i'm going to change

play01:03

this string to

play01:05

world so hello world right so if i

play01:09

save this now and open up the console

play01:12

i'm going to clear this to give us a bit

play01:13

of room

play01:14

and i'm going to run this file so go run

play01:17

main dot go and we should see these two

play01:20

statements printed

play01:21

to the console down here we see hello

play01:24

world and they're not

play01:25

on new lines because like i said print

play01:28

doesn't add a new line

play01:29

to the end of the string right here if

play01:32

we want to do that we have to manually

play01:34

do it

play01:35

and to do that we use the escape key

play01:37

which is a backslash and then

play01:38

n which stands for new line and we can

play01:40

see this is a slightly different color

play01:42

to say it's a special character or an

play01:44

escaped key

play01:45

and this will add on a new line a new

play01:48

carriage return

play01:49

down here so if i was to add on now

play01:52

another

play01:52

print statement let me just duplicate

play01:54

that and add on

play01:56

new line right here and we'll add on the

play01:58

new line as well at the end of this one

play02:00

if i was to save this now and run the

play02:03

file again

play02:04

then we should see this right here new

play02:06

line on a new line which

play02:08

we do because of this character right

play02:10

here okay so that's the print function

play02:13

all right so next let's look at the

play02:15

print line again so fmt

play02:17

dots print line like so

play02:20

and this again does pretty much the same

play02:23

thing but it's going to add

play02:24

this thing automatically at the end

play02:26

without us having to manually do it

play02:28

so i could say here hello ninjas like so

play02:32

and then i'll do another print line and

play02:35

say goodbye ninjas

play02:38

and save it let's run this and they

play02:40

should automatically be on

play02:42

separate lines and they are so i tend to

play02:45

use this a little bit more

play02:46

than this there are special occasions

play02:48

where i will use this like

play02:50

getting information from the user in the

play02:52

console but we'll see that later on

play02:54

all right then so again i'm going to

play02:56

clear this console give us a bit of room

play02:58

and then up here we'll do another

play02:59

example so what i'm going to do is just

play03:02

paste in a couple of variables here

play03:03

because i want to show you that we can

play03:04

output variables

play03:06

to the console as well using these print

play03:08

functions

play03:09

so i'm going to say fmt dot

play03:12

print line and then inside parentheses

play03:16

i'm going to start with a string and say

play03:19

my age

play03:20

is and then i'm going to do a comment

play03:22

after the string and as a second

play03:24

argument

play03:24

i'm going to output the age variable so

play03:26

we can do this we're going to output

play03:28

several different values to this

play03:31

function right here

play03:32

and comma separate them so it's going to

play03:33

say my age is

play03:35

and then whatever this age is 35 then a

play03:38

comma

play03:38

and then i'll do another string and i

play03:40

say and my name

play03:42

is and then outside of the string a

play03:44

comma and then we'll output the name

play03:46

variable

play03:47

so if i save this and run then we should

play03:51

be able to see

play03:52

all of that printed to the console my

play03:54

age is 35 and my name is

play03:56

sean awesome so that's how we output

play03:58

variables very simple

play04:00

okay that so this was print

play04:04

line and by the way this is how you do

play04:06

comments in go just the same as

play04:08

javascript and some other programming

play04:09

languages

play04:10

just double forward slash all right so

play04:13

after that i want to show you how to do

play04:15

formatted strings which are a little bit

play04:17

more complicated

play04:19

so a formatted string is a way to create

play04:21

a string with variables embedded inside

play04:24

it so we can do something

play04:25

like this where we output variables to

play04:27

the console but instead of having to

play04:29

break out of the string

play04:30

then use the variable then back into the

play04:32

string then out and then use the

play04:33

variable

play04:34

instead we can just create one string

play04:36

and embed the variables inside it

play04:38

that's what a formatted string is all

play04:40

about so let me do a comment first

play04:42

here to say print f that's the function

play04:44

name and then in parentheses i'm going

play04:46

to say

play04:46

formatted strings like so

play04:50

so how does this work well let's say fnt

play04:53

then

play04:53

print f that's the method and then

play04:56

inside here we pass in a string

play04:58

now i'm going to say my age is and then

play05:00

underscore that's where i

play05:01

later want to output a variable and

play05:04

my name is underscore again i'm going to

play05:07

output another variable right here

play05:08

so i want to output the age here and the

play05:11

name

play05:12

right here how do i do that inside a

play05:14

formatted string well i pass in extra

play05:16

arguments

play05:17

and these arguments the variables i want

play05:19

to output inside the string

play05:21

and the order matters so we're passing

play05:23

the age first and then the name

play05:25

and the way we output these is by using

play05:27

format specifiers

play05:29

right here inside the string so a format

play05:32

specifier starts with

play05:33

a percentage and then some kind of

play05:35

character now i'm going to start with

play05:38

v which is the default format for

play05:40

variables

play05:41

so what this does is take a look at this

play05:45

string first of all and says okay i've

play05:47

found this percent v

play05:48

so i'm going to look for the first

play05:50

variable because this

play05:52

is the first time i found it in the

play05:53

string and that's why the order matters

play05:55

and i'm going to output that right here

play05:57

i'm going to do the same over here

play05:59

percent v

play06:00

meaning output this in the default

play06:02

format

play06:03

looks through the string and says this

play06:05

is the second one i found i'm going to

play06:06

find the second

play06:08

value over here and output that in its

play06:10

default format

play06:11

right here so let me save this and run

play06:14

it

play06:14

go run main go and we should see the

play06:17

same string as this

play06:19

this thing right here so we output age

play06:22

right here

play06:22

and the name right here okay

play06:25

so remember this is called a format

play06:28

specifier and it's how we output

play06:30

these variables inside a formatted

play06:32

string and there's loads of different

play06:33

characters we can use with these

play06:35

now for now i'm just going to say

play06:38

percent v

play06:38

or rather percent underscore to

play06:40

represent some kind of character

play06:42

is equal to a format specifier so we

play06:45

know what that is and this

play06:47

underscore can be many different letters

play06:49

right and the different

play06:51

format specifiers output them in

play06:53

different ways

play06:54

and we're going to see a few of them now

play06:56

so let me duplicate this to do another

play06:58

example and this time i'm going to

play06:59

change this to

play07:00

q and i'm going to change this to q as

play07:02

well

play07:03

so what that does is place quotes around

play07:06

the variables

play07:07

when we output them now this is not

play07:09

going to work

play07:10

on the age because this is an integer

play07:13

and not a string

play07:14

and ideally these should be used on

play07:15

strings so let me save this

play07:17

and run it and we can see right here

play07:21

oops we need a new line first of all so

play07:23

let me add those on because

play07:24

this doesn't add new lines on

play07:26

automatically so backslash

play07:28

and then n on both of those i'm gonna

play07:30

run this again so we can see it again

play07:32

and we can see my age is hash and my

play07:35

name is sean

play07:36

so this right here hasn't worked it's

play07:39

just placing a hash instead of the

play07:41

actual age and this has worked we have

play07:43

double quotes

play07:44

around the name variable so that's what

play07:46

this does

play07:47

now if we changed age to be the string

play07:51

age then it's going to work for this

play07:53

variable as well

play07:54

and i can demo that i'm going to run

play07:56

this file again and we can see now

play07:58

we get 35 in quotes and shown in quotes

play08:01

all right then so let me change this

play08:02

back to just a number

play08:04

35. so let me do another example

play08:08

i'm going to come down here and say oops

play08:11

onto the next line

play08:12

fmt dot print

play08:15

f and this time i'm going to say age

play08:22

if i can type is of type

play08:25

and then i'm going to use percentage t

play08:27

and what this does

play08:28

is get us the type of variable

play08:32

so if i put in here age

play08:35

like this then it's going to look at the

play08:37

first variable we pass in

play08:39

and it's going to output the type of

play08:40

that variable so

play08:42

if i save it and run this let me clear

play08:44

first to give us some room

play08:46

and run the file then we can see

play08:49

age is of type int all right

play08:53

all right there so what about outputting

play08:55

things like floats

play08:57

well let's do that i'm going to say fmt

play09:00

dot print f and then another string

play09:04

and i'll say you scored then underscore

play09:07

for now

play09:08

points like so we need to add on our new

play09:12

line

play09:12

characters keep forgetting to do that

play09:15

okay

play09:16

so what i want to do is output a float

play09:18

here now i don't have a float variable

play09:20

but we can pass the value directly

play09:22

in here so i could say for example two

play09:24

two five point five five that is a float

play09:26

right

play09:27

now to output a float i could say

play09:30

percentage

play09:33

f that stands for float right now if i

play09:36

save this

play09:37

and run it we're gonna see that float

play09:38

but we're gonna see loads of decimal

play09:40

points over here

play09:41

so we can limit the number of decimal

play09:43

points we output

play09:45

by putting a number between the percent

play09:48

and the f so if i want it to two decimal

play09:51

points i could say

play09:52

not point two if i want it to one i can

play09:54

say not point one

play09:56

so let's give this a whirl i'm gonna

play09:57

save it and run it

play09:59

and we should see the same thing but

play10:01

this time it's rounded it to one decimal

play10:03

point it's rounded up to six here

play10:05

because five rounds up to six all right

play10:08

cool so that is formatted

play10:12

strings there are other characters we

play10:14

can use here and different format

play10:15

specifiers

play10:16

and what i'll do is leave a link down

play10:18

below to a page with all of these

play10:20

different format specifiers listed so

play10:22

you can check them out for yourself

play10:23

and play around with them alright so the

play10:25

final method i want to show you

play10:27

is called sprint f so sprint f

play10:30

is very much like printf except it saves

play10:33

the string in a variable for us so we

play10:35

can do something with it later on

play10:37

so let me do a comment sprint f so save

play10:40

printf basically so we can save

play10:42

formatted strings

play10:44

and then below that we're going to do an

play10:45

example so i'm going to say

play10:47

fmt dot sprint f this time

play10:51

and then all i'm going to do is pass in

play10:52

the same thing

play10:54

as this one right here so let me grab

play10:56

that

play10:57

and paste in right here so we're

play10:58

outputting this string

play11:00

and then we have the age for this and

play11:03

the name

play11:03

for this right so the same example as

play11:05

above only this time

play11:07

this is not going to directly print it

play11:10

out to the console instead it returns

play11:12

that formatted string

play11:13

to us and we can store it in a variable

play11:16

so i could say

play11:17

var str call it what you want is equal

play11:20

to fmt dot sprint f

play11:24

and this returns us that string now if i

play11:26

hover over this we get an error because

play11:27

we're not using it

play11:28

i can print this to the console by

play11:31

saying fmt

play11:32

dot print line and then we're going to

play11:35

output the string

play11:37

so we'll say the saved string

play11:41

is colon and then comment and we'll

play11:43

output str

play11:45

so if i save this now open up the

play11:47

console

play11:48

run this again it should work we can see

play11:51

the saved

play11:51

string is and then this is the saved

play11:54

string returned to us

play11:56

right here awesome so like i said

play11:58

there's

play11:59

many format specifiers we've just seen a

play12:02

few of them and if you want to check out

play12:04

more

play12:04

that link is going to be down below

play12:06

which shows all of the different format

play12:08

specifiers

play12:08

right here so you can browse through

play12:10

those and play around with some of them

play12:12

but

play12:12

we've covered all of the ones that we'll

play12:14

probably use in

play12:16

the rest of this tutorial series and if

play12:17

we cover any more i will explain them

play12:20

at the time anyway next up we're going

play12:22

to talk about arrays and slices

Rate This

5.0 / 5 (0 votes)

الوسوم ذات الصلة
Go programmingstring formattingtutorialcoding basicsprintf functionvariablesconsole outputformat specifierscoding lessonsGo language
هل تحتاج إلى تلخيص باللغة الإنجليزية؟