unable to understand how the group name is defined based on the chat room name while making a chat application using channels

Question:

self.room_group_name = "chat_%s" % self.room_name
This is the line of code that defines the room group name from the room_name in the official tutorial on the channels website.
(https://channels.readthedocs.io/en/stable/tutorial/part_2.html)

I am unable to understand what "chat_%s" % self.room_name" means.
Would appreciate any explanation of what this bit of code exactly does.

Asked By: Saket Vempaty

||

Answers:

"chat_%s" % self.room_name

is an expression for formatting strings. The %s is a replaceable parameter which gets populated with the values passed after the %.

Python3 has other formatting methods available that are roughly equivalent:

f"chat_{self.room_name}"

f"chat_{self.room_name}" is an f-string. f-string is a shortcut for the string format function:

"chat_{room_name}".format( room_name = self.room_name ) 

Essentially, the formatting syntax you are asking about is this:

"template" % (param1, param2...) 

The parameters in the template get replaced in order. This is essentially an older deprecated way of formatting strings with variable interpolation.

Answered By: Mark

This is string formatting [Python-doc]. It will produce a string where it will replace the %s with the str(…) on self.room_name. If self.room_name is thus 'foo', then it will produce a string 'chat_foo'.

Nowadays f-strings [pep-498] are used more commonly, so then one works with;

self.room_group_name = f'chat_{self.room_name}'
Answered By: Willem Van Onsem
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.