开始使用Python中的类,但无法让子字符串工作

问题描述 投票:0回答:1
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')

当我运行代码时,随机消息不会缩短:

['tommorow will be a good day']
28
['tommorow will be a good day']

我正在尝试Python中的类,并试图在随机选择一条消息后去掉消息列表开头和结尾的列表符号。但是我不明白为什么 python 在指定范围后不只打印部分消息。

我尝试使用整数代替

[:self.message_len]
但没有成功。

python string class substring self
1个回答
0
投票

问题本身发生在处理过程中

random_message
- 你的方法有点错误,因为当你使用
random.sample(self.futures, k=1)
时 -> 它将返回一个包含一个元素的列表,而不是一个字符串;因此你在输出中遇到了括号。

正确的方法是在尝试对字符串进行切片之前从列表中提取字符串本身。

这将是修改你的方法的一种方式: 随机导入

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')

我们在这里做了什么:

  • random.sample(self.futures, k=1)
    替换为
    random.choice(self.futures)
    。 random.choice 返回从列表中随机选择的单个元素,而不是列表。
  • 我们删除了对字符串的转换,以及减去 3 个字符(
    - 3
    ),这最有可能导致问题,因为它纯粹基于列表表示的长度而不是实际消息。
© www.soinside.com 2019 - 2024. All rights reserved.