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.

1

There are 1 best solutions below

0
str1ng On BEST ANSWER

The issue itself, takes place inside of the handling random_message - you kind of had wrong approach because when you're using random.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

class MyClass:
    def future(self):
        self.futures = [
            'you will die soon',
            'you will live a long and prosperous future',
            'what you look for is nearby',
            'tomorrow will be a good day'
        ]
        # Get a random message and extract it from the list
        self.random_message = random.choice(self.futures)
        print(self.random_message)

        # Now, you can work with self.random_message as a string
        # If you want to modify its length or do other string operations, do it here
        # For example, to get a substring of the message:
        self.message_len = len(self.random_message) - 3
        self.random_message = self.random_message[:self.message_len] 
        print(self.random_message)

        self.message.config(text=self.random_message, bg='pink')

What we did here:

  • Replaced random.sample(self.futures, k=1) with random.choice(self.futures). random.choice returns a single, randomly selected element from the list, not a list.
  • We removed the conversion to a string, and the substraction of 3 chars, ( - 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.