简体   繁体   English

Python:将 print() 函数中的 None 值转换为字符串

[英]Python: Converting a None value from the print() function into a string

I am trying to write a function that takes a list value as an argument and returns a string with all the items separated by a comma and a space, with 'and' inserted before the last item.我正在尝试编写一个函数,该函数将列表值作为参数并返回一个字符串,其中所有项目以逗号和空格分隔,并在最后一项之前插入“和”。

For example, passing the list 'spam' which contains the values ['apples', 'bananas', 'tofu', 'cats'] , would return: "apples, bananas, tofu, and cats" .例如,传递包含值['apples', 'bananas', 'tofu', 'cats']的列表 'spam' 将返回: "apples, bananas, tofu, and cats"

I wrote the following code:我写了以下代码:

def thisIsIt(alist):
  alist.insert(-1, 'and')
  alist1 = alist[:-2]
  alist2 = alist[-2:]
  for item in alist1:
    print(item, end = ", ")

  for item in alist2:
    print(item, end = " ")

which does return: apples, bananas, tofu, and cats.确实会返回:苹果、香蕉、豆腐和猫。 However it is printed as a Nonetype, instead of a string.然而,它被打印为一个 Nonetype,而不是一个字符串。 How can I correct this please?请问我该如何纠正?

In any case, if you want a different solution and want it to return a String you can use the power of str.join() in python:在任何情况下,如果你想要一个不同的解决方案并希望它返回一个 String 你可以在 python 中使用str.join()的强大功能

def thisIsIt(alist):
  resultString = ", ".join(alist[:-2] + [" and ".join(alist[-2:])])
  return resultString

myList = ['apples', 'bananas', 'tofu', 'cats']
myListAsString = thisIsIt(myList)
print(myListAsString)
#apples, bananas, tofu and cats 

Code :代码 :

list_sample = ['apples', 'bananas', 'tofu', 'cats']

for i in range(0,len(list_sample)):
    if i < len(list_sample)-1 and i != len(list_sample)-2:
        print(list_sample[i],end = ", ")
    elif i == len(list_sample)-2:
        print(list_sample[i],end = " and ")
    else:
        print(list_sample[i])

Output :输出 :

apples, bananas, tofu and cats 

I have tried KISS .我试过KISS (Keep It Simple Stupid) (保持简单愚蠢)

spam = ['apples', 'bananas', 'tofu', 'cats', 'oranges']

def newlist(x):
    myStr = ''    
    if len(x) != 0:
        for i in range(len(x)-1):
            myStr += str(x[i]+', ')
    return(myStr + 'and ' + x[-1]) 

newlist(spam)

I think for beginners like me try to keep things simple, guys!我认为对于像我这样的初学者尽量保持简单,伙计们!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM