TextVar

TextVar #

Constructor #

The TextVar object is a sub-class of str. It makes it easier to concatenate strings.
Its constructor takes 0 to n strings and concatenates them by adding a space between them.
It will unpack any nested list or tuple that is provided as argument.

text_1 = TextVar()
# ""

text_2 = TextVar("It was the best sandcastle he had ever seen.")
# It was the best sandcastle he had ever seen.

text_3 = TextVar("All you need to do", "is pick up the pen", "and begin.")
# All you need to do is pick up the pen and begin.

text_4 = TextVar("He loved eating", ("his", "bananas"), "in hot dog buns.")
# He loved eating his bananas in hot dog buns.

Appending #

You must use the ‘+=’ operator to append text to your string. This works the same as the constructor.

name = "Mary"
city = "New-York"
number_of_children = 2

text = TextVar()

text += name, "lives in", city, "."

if number_of_children == 0:
  text += "She does not have children."
elif number_of_children == 1:
  text += "She has one child."
else:
  text += "She has", str(number_of_children), "children."

print(text)
# Mary lives in New-York . She has 2 children.

Now you may have noticed the space we introduced before the dot in the first sentence. This is not correct and should not be present in the final text, so what are the options?

You could use a simple trick like this one:

text += name, "lives in", city + "."

This will make sure no space will be added before the dot, however there is a better way to do it using the text attribute from the NlgTools object that will correct any syntaxic mistakes in your text. We will see it in the next chapter.