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.
CodePudding user response:
"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.
CodePudding user response:
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}'