简体   繁体   English

PYTHON3:如何打印出用户输入的字符串并以逗号分隔打印出来?

[英]PYTHON3: How to print out user input string and print it out separated by a comma?

My current code is: 我当前的代码是:

def my_input(): 
    my_string = input("Important ions are: ")
    for i in my_string:
        print(my_string, sep=",")

my_input()

So I am trying to write a program, whereby the user is prompted "Important elements are:" and is expected to input: 因此,我试图编写一个程序,提示用户“重要元素是:”,并期望输入:

Na K Ca Mg Mn(all on one line separated by single spaces): Na K Ca Mg Mn(全部用单行隔开):

Then, I want my code to print out the following: 然后,我希望我的代码打印出以下内容:

Important ions are: Na, K, Ca, Mg and Mn

Instead, with my current code, I am getting the following output: 相反,使用我当前的代码,我得到以下输出:

Na K Ca Mg Mn
Na K Ca Mg Mn
Na K Ca Mg Mn
Na K Ca Mg Mn
Na K Ca Mg Mn
Na K Ca Mg Mn
Na K Ca Mg Mn
Na K Ca Mg Mn
Na K Ca Mg Mn
Na K Ca Mg Mn
Na K Ca Mg Mn
Na K Ca Mg Mn
Na K Ca Mg Mn

I am confused as to why/how this is the output printed that many times. 我对于为什么/如何多次打印输出感到困惑。 I think I get why it is not being separated by a comma, is it because it is treating the input as 1 string? 我想我为什么不将其用逗号分隔,是因为它将输入视为1个字符串? And I guess in order to print out my desired output, I'd have to do like 而且我想为了打印我想要的输出,我必须像

print("Important ions are" + my_string)

But I know that cannot be correct and then how could I get to print out the input, separated by commas and add an "and" in between as the desired output displayed above?? 但是我知道那是不正确的,然后我如何打印出用逗号分隔的输入并在上面显示的所需输出之间添加“和”呢?

First, your guess is right, you have to add the string "Important ions are" when you print your output. 首先,您的猜测是正确的,在打印输出时必须添加字符串"Important ions are"

Besides, you used 'my_string' (all ions input) in your for-loop, that's why you get 'Na K Ca Mg Mn' printed for multiple times. 此外,在for循环中使用了'my_string' (所有离子输入),这就是为什么多次打印“ Na K Ca Mg Mn”的原因。

What you need will look like this 您需要的看起来像这样

def my_input(): 
    my_string = input("Important ions are: ")
    ions = my_string.split(' ')
    print("Important ions are: ", end='')
    for j, i in enumerate(ions):
        if j == 0:
            print(i, end='')
        if j == (len(ions) - 1):
            print(' and ' + i)
        else:
            print(', ' + i, end='')

my_input()

Output: 输出:

# >>> my_input()
# Important ions are: Na K Ca Mg Mn
# Important ions are: Na, Na, K, Ca, Mg and Mn

Here is an alternative version 这是替代版本

def my_input(): 
    my_string = input("Important ions are: ")
    ions = my_string.split() # Split input by whitespace characters
    print('Important ions are:', ', '.join(ions))

my_input()
  • ions stored a list of the input ions. ions存储输入离子的列表。
  • ', '.join(ions) returns a string of ions separated by a comma followed by a space. ', '.join(ions)返回一串离子,用逗号分隔,后跟一个空格。
  • print is used to print the prefix Important ions are: and the joined string. print用于打印前缀Important ions are:和连接的字符串。 Note that print use a space to separate the given arguments. 请注意,print使用空格分隔给定的参数。

To show and between the last two item, the last item should be printed separately. 要显示and在最后两个项目之间,应单独打印最后一个项目。 Here is the updated version. 这是更新的版本。

def my_input(): 
    my_string = input("Important ions are: ")
    ions = my_string.split() # Split input by whitespace characters
    print('Important ions are:', ', '.join(ions[:-1]), 'and', ions[-1]))

my_input()
  • ions[:-1] : slicing the ions list up to the second last item. ions[:-1] :将ions列表切至倒数第二个项目。
  • ions[-1] : the last item. ions[-1] :最后一项。

See slicing on Python tutorial . 请参阅在Python上切片教程

However, the code will produce strange result or errors if only one ion or no ion is entered, respectively. 但是,如果分别输入一个离子或不输入离子,该代码将产生奇怪的结果或错误。 To fix the issue, the length of the ions should be assesed: 要解决此问题,应评估ions的长度:

def my_input(): 
    my_string = input("Important ions are: ")
    ions = my_string.split() # Split input by whitespace characters
    if len(ions) > 1:
        print('Important ions are:', ', '.join(ions[:-1]), 'and', ions[-1]))
    elif lrn(ions) == 1:
        print('Important ion is:', ions[0])
    else:
        print('No ions are important')
my_input()

You could try this: 您可以尝试以下方法:

import re
def my_input(): 
    my_string = input("Important ions are: ").split()   # storing the input as elements of a list
    w = " ".join(my_string)                                     # joining all the elements in the list  
    print("Important ions are: ", re.sub(" ",", ",w[0:-2]) +'and '+ my_string[-1])  # appending the last element after inserting ', ' and 'and'

my_input()

This should give you the output exactly the way you wanted. 这应该为您提供完全所需的输出。 The reason why your code prints the input repeatedly is because of this line: 您的代码重复打印输入的原因是由于以下这一行:

 print(my_string, sep=",")

It just prints the whole input as many times as there elements in the input. 它只是将整个输入打印与输入中的元素一样多的次数。 Also, sep= "," won't work in loops. 另外,sep =“,”不会循环工作。

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

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