Python raw_input ignore newline

為{幸葍}努か 提交于 2019-11-30 19:10:55

Because raw_input only takes one line from input you need to create a loop:

names = []
print('Shoot me some names partner: ')
while True:
    try:
        name = raw_input()
    except KeyboardInterrupt:
        break
    names.append(name)

print('What do you want to do?')
print('1 - format names for program 1')
print('2 - format names for program 2')

first_act = raw_input('Enter choice: ')

print(names)
print(first_act)

Test run:

Shoot me some names partner: 
name1
name2
^CWhat do you want to do?
1 - format names for program 1
2 - format names for program 2
Enter choice: 1
['name1', 'name2']
1

Note I've used ^C (Ctrl-C) here to indicate the end of the input.

I am not sure what you are trying to ask but when you use raw_input(), it strips a trailing newline.

And the doc says the same too.

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!