Python 每次从列表中获取30个字符的字符串

Python 每次从列表中获取30个字符的字符串,python,string,list,Python,String,List,我有一个问题,我只想在每次运行时获取最多包含30个字符的字符串 import random test=["test1 up to 30 characters", "test2 passing 30 characters easy", "test3 up to 30 characters", "test4 passing 30 characters easy"] random.shuffle(test) if len(test[0]) <= 30:

我有一个问题,我只想在每次运行时获取最多包含30个字符的字符串

import random
test=["test1 up to 30 characters",
      "test2 passing 30 characters easy",
      "test3 up to 30 characters",
      "test4 passing 30 characters easy"]
random.shuffle(test)
if len(test[0])  <= 30:
    print test[0]
elif len(test[0])  >= 30:
    print "Shit"
    print len(test[0])
随机导入
test=[“test1最多30个字符”,
“test2轻松通过30个字符”,
“test3最多30个字符”,
“测试4通过30个字符容易”]
随机洗牌(测试)
如果len(测试[0])=30:
打印“狗屎”
打印透镜(测试[0])
编辑:************************************************************************************************************************************************************************************

在测试中,我将有一个如下所示的变量:

import random
test=["test1 up to "+variable+" characters",
      "test2 passing "+variable+" characters easy",
      "test3 up to "+variable+" characters",
      "test4 passing "+variable+" characters easy"]
random.shuffle(test)
if len(test[0])  <= 30:
    print test[0]
elif len(test[0])  >= 30:
    print "Shit"
    print len(test[0])
随机导入
test=[“test1最多”+变量+“个字符”,
“test2传递”+变量+“字符容易”,
“test3最多可包含“+变量+”个字符”,
“test4传递”+变量+“字符容易”]
随机洗牌(测试)
如果len(测试[0])=30:
打印“狗屎”
打印透镜(测试[0])
这个变量将是一个混合的字符数,从5到我不知道,比如说10

我希望程序从列表中选择总共最多包含30个字符的字符串。您的解决方案只是打印出包含最多30个字符的字符串,就这样。我希望它返回并在列表中找到一个字符串,该字符串每次为每个变量提供总共30个字符。我真的希望你能理解,我很难理解自己

编辑******************************************************************************************************************************************************************************************

好的,我这样做了:

import random
test=["test1 up to 30 characters",
      "test2 passing 30 characters easy",
      "test3 up to 30 characters",
      "test4 passing 30 characters easy"]
random.shuffle(test)
print [x for x in test[0:1] if len(x) < 30]
随机导入
test=[“test1最多30个字符”,
“test2轻松通过30个字符”,
“test3最多30个字符”,
“测试4通过30个字符容易”]
随机洗牌(测试)
如果len(x)<30,则在测试[0:1]中打印[x代表x]

它做了我想要的,但仍然得到空白,比如空[]

你不能同时拥有这两个
=
,也就是说,你不能同时拥有这两个
=
。本质上,第二个
if
应该是一个
else
,因为如果它不小于或等于30,剩下什么?

你不能同时拥有这两个
=
,也就是说,你不能同时拥有这两个
=
。本质上,第二个
if
应该是一个
else
,因为如果它不小于或等于30,剩下什么?

使用列表理解:

print [x for x in test if len(x) < 30]
打印[x代表x,如果len(x)<30]

使用列表理解:

print [x for x in test if len(x) < 30]
打印[x代表x,如果len(x)<30]

+1,但您可能想要。此解决方案是正确的,您只需将列表理解保存在某个位置,而不是将其打印。..uau(列表理解)谢谢,非常有用。+1,但您可能想要。此解决方案是正确的,您只需将列表理解保存在某个位置,而不是将其打印。..uau(列表理解)谢谢,非常有用。您的编辑没有任何区别-您得到的解决方案仍然有效,因为您仍然会得到一个字符串列表,每个字符串仍然有一个长度(包括变量的长度)我明白了,我会给它一个测试…非常感谢。你的编辑没有任何区别-你得到的解决方案仍然有效,因为你仍然有一个字符串列表,每个字符串仍然有一个长度(包括变量的长度)。我明白了,我会给它一个测试…非常感谢。