Python raw_input ignore newline

前端 未结 2 1245
生来不讨喜
生来不讨喜 2021-01-05 03:10

Is there a way to ignore newline characters in data entered through raw_input? I am trying to use raw_input to input a list of strings that are copied and pasted from a spr

相关标签:
2条回答
  • 2021-01-05 04:00

    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.

    0 讨论(0)
  • 2021-01-05 04:07

    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.

    0 讨论(0)
提交回复
热议问题