![](/img/trans.png)
[英]Python: Print first two characters of each item in a list. (without spaces)
[英]Print the first three characters of each item in the list which has more than 5 characters
items = ["Apple", "Banana", "Cherry", "Date", "Eggfruit", "Fig"]
for word in items:
print(word[:3])
#prints the first three characters of each item
def string_k(k, str):
string = []
text = str.split(" ")
for x in text:
if len(x) > k:
string.append(x)
return string
k = 6
str = "Apple, Banana, Cherry, Date, Eggfruit, Fig"
print(string_k(k, str))
#This prints out every item in the list that has more than five characters
這類似於我的第一個問題 - 我有兩個單獨的代碼,但我不明白如何將它們組合在一起以獲得我需要的輸出
您可以在此處使用filter
。
items = ["Apple", "Banana", "Cherry", "Date", "Eggfruit", "Fig"]
for _str in filter(lambda x:len(x)>=5,items):
print(_str[:3])
輸出:
App
Ban
Che
Egg
這應該比您的代碼更有效。
items = ["Apple", "Banana", "Cherry", "Date", "Eggfruit", "Fig"]
for i in range(0, len(items)):
if len(i) >= 5:
print(i[:3])
items = ["Apple", "Banana", "Cherry", "Date", "Eggfruit", "Fig"]
for item in items:
if len(item) >= 5:
print(item[:3])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.