What does Python mean and work for rstrip?

Asked 2 years ago, Updated 2 years ago, 20 views

◆ This is a question about Python's standard input() statement.◆
Example sentence:

import random

line=input().rstrip().split(",")
list = ['Okichi', 'Nakayoshi', 'Kichi', 'Bad']
num=len(list)
print(list)
print(list[random.randrange(num)]

■ Values entered: Okichi, Nakayoshi, Kichi, Bad

◆ Please tell me the meaning and function of rstrip() in the third line of the example above.
  Also, could you tell me about the split(", ") after that?

python

2022-09-30 19:29

1 Answers

These are the answers.
Each string entered from a standard input (typically a keyboard) applies its own actions.

input([prompt])

If the prompt argument exists, it is written to the standard output except for the last line feed.The function then reads one line from the input, converts it into a string, and returns it (except for the last new line). When EOF is loaded, an EOFError is sent.Example:

>>s=input('-->')  
-->Monty Python's Flying Circus
>>s  
"Monty Python's Flying Circus"

str.rstrip([chars])

Returns a copy of the end of the string that has been removed.The chars argument is a string that specifies the character set to be removed. If chars is omitted or None, the blank characters are removed. The chars string is not a suffix, and any combination of characters contained in it will be ripped off:

>>>'space'.rstrip()
'   spatial'
>>>'missippi'.rstrip('ipz')
"miss".

str.split(sep=None,maxsplit=-1)

Returns a list of words separated by a string sep as a delimiter string.If maxsplit is given, it splits up to maxsplit times (that is, the list can be maxsplit+1 elements), and if maxsplit is not given or -1, there is no limit to the number of splits (as many as possible).

If sep is given, consecutive delimiters are not put together and are considered to separate empty strings (for example, '1, 2,'.split(', ') returns ['1', '', '2'].The sep argument can be multiple characters (for example, '1<2>3'.split('>') returns ['1', '2', '3'].If you split an empty string with a delimiter, it returns '" ].

>>>'1,2,3'.split(',')
['1', '2', '3']
>>>'1,2,3'.split(',',maxsplit=1)
['1', '2,3']
>>> '1, 2, 3, '.split(', ')
['1', '2', '', '3', '']

I found an article with similar usage and explanation, so I added:
There is no exact same example.

Tips you want to know when programming games with Python 3


2022-09-30 19:29

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.