2016-07-18 10 views
-7

私は整数入力から空白を削除してリストに格納したいと思います。Pythonではいつsplit()を使うべきですか?

t = raw_input().split() 
numbers = [int(x.strip()) for x in t] 
numbers = sorted(numbers) 
print numbers 

ただし、strip()を使用しないと出力は変わりません。私がなぜstrip()を使うべきか説明してください。私はフォーラムのいくつかの記事を見て、人々はまた、頻繁にstrip()を使用します。私はsplit()が空白を取り除いてすべての数値を返し、strip()も同じ仕事をすることを理解しています。

ありがとうございます!

+1

[ 'str.split'](https://docs.python.org/3/library/stdtypes.html#str.split)対['str.strip'](https://docs.python.org/3/library/stdtypes.html#str。ストリップ: – poke

+0

入力: '' 1 2 3 ''、' split: '[' 1 '、' 2 '、' 3 ']ストリップ:' '1 2 3'' –

+1

[' split' ](https://docs.python.org/3/library/stdtypes.html#str.split)と['strip'](https://docs.python.org/3/library/stdtypes.html#str .strip)これらの関数が同じことをすると思いますか? – Matthias

答えて

1

私は混乱を理解していません。 split()関数は、指定された引数のすべての出現を取り除いて、文字列のすべての部分のリストを返します。

たとえば、次の文字列があるとします。 "Hello world!" [ "地獄"、 "W"、 "RLD!"]のコードで

str = "Hello world!" 
split_str = str.split("o") 

print "str has type", type(str), "with the value", str, "\n" 
print "split_str has type", type(split_str), "with the value", split_str 

そして、出力してから出力がされます( "O")、分割することで、この1を分割

文字列の値がHello worldの文字列です。

split_strは、[「地獄」、「W」、「RLD!」]の値を持つタイプのリストを持っている

をので、あなたはスペースで区切っ異なる整数のシーケンスを表す文字列を持っている場合:このソリューションで動作する可能性があります。

input_integers = raw_input().split(" ") # splits the given input string 
numbers = [int(x) for x in input_integers] # iteration to convert from string to int 
numbers = sorted(numbers) # makes a sort on the integer list 
print numbers # display 

これは非常に基本的な文字列ですので、次回はドキュメントを読むようにしてください。これは、あなたのソリューションを得るために読むことができる最初のツールです。

0

split(split_item)はsplit_item

strip(strip_item)による入力を分割してリストを返す先頭と後端からstrip_itemが削除され、残りの項目を返します。

例:

a = " how are you "

a.split()['how', 'are', 'you']

a.strip()を与えるだろうが'how are you'

を与えるあなたは()

a.split("o")ワット内の任意の文字列を指定することができます病気に与える[' h', 'w are y', 'u ']

a.strip("o")与える' how are you ' - >同じ文字列

関連する問題