我遇到問題,我只想獲取每次運行時最多包含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])
修改:**************************************** ************************************
在測試中,我將有一個變量會是這個樣子:
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])
該變量將是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]
據我想要做什麼,但仍然得到空白,像空[]
你的編輯都沒有區別 - 你已經被賦予仍然可以工作,你仍然落得一個字符串列表的解決方案,其中每一個仍然具有長度(其中將包括變量的長度) –
我明白了,我給它一個測試...非常感謝。 –