I've recently begun experimenting with classes in Python and I'm facing a challenge with string slicing. Here's a snippet of my code
def future(self):
self.futures = ['you will die soon','you will live a long a
prosperous future','what you look for is nearby','tommorow will
be a good day']
self.random_message = (random.sample(self.futures, k=1))
print(self.random_message)
self.message_len = (len(str(self.random_message)) - 3)
print(self.message_len)
self.random_message = self.random_message[:self.message_len]
print(self.random_message)
self.message.config(text=self.random_message, bg='pink')
When I run this method, the output is not as expected. For example:
['tomorrow will be a good day']
28
['tomorrow will be a good day']
The goal is to remove the list brackets from the randomly selected message and then display it. However, I can't seem to modify the string correctly using slicing. I have attempted using direct integers in place of [:self.message_len], but it didn't work as expected.
Any insights on why the slicing isn't working as intended and how I can achieve the desired output would be greatly appreciated.
The issue itself, takes place inside of the handling
random_message- you kind of had wrong approach because when you're usingrandom.sample(self.futures, k=1)-> it will be returning a list with one element, and not a string; therefore you're encountering brackets in your output.The correct approach to this would be extraction of string itself from the list, before you even try to slice it.
This would be one way of modification of your method: import random
What we did here:
random.sample(self.futures, k=1)withrandom.choice(self.futures). random.choice returns a single, randomly selected element from the list, not a list.- 3), this was the most likely causing an issue because, it was purely based on the length of the list representation and not actual message.