Ren'Py renpy.random.choice and variables

LoafyLemon

Witch Trainer Silver
Game Developer
Jul 1, 2017
577
1,637
Is it possible to read variables through renpy.random.choice function? As of now it prints raw variable [name] but it should print Steve instead.

Example code:

Python:
define npc = Character("Jake")

$ name = "Steve"
$ Text = renpy.random.choice([
    "Okay, [name].",       
    "Alright, [name].",
    "If you say so, [name]."
    ])

npc "[Text]"
 

smix8

Newbie
Sep 14, 2016
48
286
this should work

Code:
init:
    define npc = Character("Jake")

    $ name = "Steve"
    $ randomtext = renpy.random.choice([
        "Okay, [name!t].",       
        "Alright, [name!t].",
        "If you say so, [name!t]."
        ])
        
label start:
    npc "%(randomtext)s"
 

xj47

Member
Nov 4, 2017
241
409
you can achieve the same effect using python string interpolation. Basically if you have a string like "Hello %s", then "Hello %s" % "there" would produce a "Hello there" string. So you add a placeholder with '%s' and insert a value with the '%' operator. (that's the short explanation anyway)

In your example you could write:

Code:
define npc = Character("Jake")

$ name = "Steve"
$ Text = renpy.random.choice([
    "Okay, %s." % name,       
    "Alright, %s." % name,
    "If you say so, %s." % name
    ])

npc "[Text]"
or


Code:
define npc = Character("Jake")

$ name = "Steve"
$ Text = renpy.random.choice([
    "Okay, %s.",       
    "Alright, %s.",
    "If you say so, %s."
    ]) % name

npc "[Text]"
In example 1 the substitution is performed when the list is build while in example 2 the substitution is performed after an item has been picked from the list.
 

LoafyLemon

Witch Trainer Silver
Game Developer
Jul 1, 2017
577
1,637
All three examples work flawlessly. I ended up using xj47's second method because it suits my needs best and seems to be the least performance heavy. Thank you both for help!
 

anne O'nymous

I'm not grumpy, I'm just coded that way.
Modder
Donor
Respected User
Jun 10, 2017
10,976
16,231
All these solutions are great, but no one thought about the (apparently not this) obvious : The name is a constant in all the strings.

Code:
init python
   name = "Steve"
        
label start:
    $  text = renpy.random.choice( [ "Okay, ",  "Alright, ","If you say so, " ] )
    npc "[text][name]."
or even :
Code:
label start:
    npc "%s [name]." % renpy.random.choice( [ "Okay, ",  "Alright, ","If you say so, " ] )