0

I don't understand why programmers use %s, when they can simply just add the variable name to the print statement. I mean its less work to type in the variable name instead of " ...%s" % name) "

Example:

# declaring a string variable
name = "David"
 
# append a string within a string
print("Hey, %s!" % name)`

Why do Programmers not type in instead:

# declaring a string variable
name = "David"

# printing a salutation without having to append a string within a string:
print("Hey," + " " + name + "!")`
```

1
  • Personally, I find the %-formatted version easier to read in this case, and that counts for a lot. But I find the f-string version even easier to read (print(f"Hey, {name}!")), and that's generally what I would use in cases like this. Commented Nov 28, 2022 at 15:00

2 Answers 2

1

There may be some performance difference, but it mostly comes down to preference.

The most modern approach is to use f-strings. With your example this would look like this:

# declaring a string variable
name = "David"

# format print using f-string
print(f"Hey, {name}!")

This way there is no %s not is there need for all the extra + symbols and spaces.

Good Luck!

0

In programming languages such as C, we use %s to use a specific string stored in a variable while printing another string, for eg., in C language:

// suppose x='John Doe'
// to print my name along with another string
printf("My name is %s", x); // Output: My name is John Doe

Same works in Python along with the method you specified.

There is also a method known as f-string Eg:

name="John Doe"
print(f"My name is {name}") # output: My name is John Doe

Another method would be .format method Eg:

name="John Doe"
print("My name is {}".format(name)) # output: My name is John Doe

Hope this helps

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.