Issue
I have the following Python code that prints data based on a template.
In the template, each selection is preceded by empty brackets, like this:
-[ ] selection one
-[ ] selection two
-[ ] selection three
Is there a way to change my script so that it increments with letters?
Like:
a. selection one
b. selection two
c. selection three
I tried using something like s = bytes([ch[0] + 1])
but I kept encountering a bunch of errors.
Here is my script:
def __str__(self):
# show the correct order (noted by Sarah)
self.options.sort(key=attrgetter('order'))
# make sure it supports multiple correct selections
correct_selection = ", ".join([
str(selection)
for selection
in self.options
if selection.correct
])
# also, make sure it substitutes only the known values (see Tompei for ?)
return _TEMPLATE.safe_substitute({
'dilemma_ethos': self.text,
'options': "\n".join([f'-[ ] {option}' for option in self.options]),
'correct_selection': correct_selection,
})
Solution
This is an example of how you could do it assuming that the template is a string (but as noted it won't work beyond z)
template_1 = """-[ ] selection one
-[ ] selection two
-[ ] selection three"""
def convert(template):
return '\n'.join([f"{chr(i + 97)}. {line[5:]}" for i, line in enumerate(template.split('\n'))])
print(convert(template_1))
This below does the same thing, but is easier to read:
template_1 = """-[ ] selection one
-[ ] selection two
-[ ] selection three"""
def convert(template):
new_list = []
template_list = template.split('\n')
for count, line in enumerate(template_list):
new_list.append(f"{chr(count + 97)}. {line[5:]}")
separator = '\n'
return separator.join(new_list)
print(convert(template_1))
The function returns with a string containing the converted template.
Answered By - Lee-xp
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.