>>> my_str.rstrip(';').split(';')
最初の文字列の右端から;
を削除:
s.rstrip(';').split(';')
また(また、文字列の末尾に見出されなかった空の要素を濾別する)filter()
を使用することができ。しかし、文字列の末尾に ";
"文字があるため、最終的に空の要素を避けたいと思っているときには、私の意見では上記の方法が最もクリーンです。
EDIT:(上記静止filter()
を使用するよりも正確である。)上記以外実際にはより正確には、以下のアプローチである。
(s[:-1] if s.endswith(';') else s).split(';')
これが最後の要素を除去し、そして場合のみであろうこと空の状態になります。
テストあなたは、彼らが異なる結果を与えることを、表示されますすべての3つのソリューション:
>>> def test_solution(solution):
cases = [
'James;Joseph;Arun;',
'James;;Arun',
'James;Joseph;Arun',
';James;Joseph;Arun',
'James;Joseph;;;',
';;;',
]
for case in cases:
print '%r => %r' % (case, solution(case))
>>> test_solution(lambda s: s.split(';')) # original solution
'James;Joseph;Arun;' => ['James', 'Joseph', 'Arun', '']
'James;;Arun' => ['James', '', 'Arun']
'James;Joseph;Arun' => ['James', 'Joseph', 'Arun']
';James;Joseph;Arun' => ['', 'James', 'Joseph', 'Arun']
'James;Joseph;;;' => ['James', 'Joseph', '', '', '']
';;;' => ['', '', '', '']
>>> test_solution(lambda s: filter(bool, s.split(';')))
'James;Joseph;Arun;' => ['James', 'Joseph', 'Arun']
'James;;Arun' => ['James', 'Arun']
'James;Joseph;Arun' => ['James', 'Joseph', 'Arun']
';James;Joseph;Arun' => ['James', 'Joseph', 'Arun']
'James;Joseph;;;' => ['James', 'Joseph']
';;;' => []
>>> test_solution(lambda s: s.rstrip(';').split(';'))
'James;Joseph;Arun;' => ['James', 'Joseph', 'Arun']
'James;;Arun' => ['James', '', 'Arun']
'James;Joseph;Arun' => ['James', 'Joseph', 'Arun']
';James;Joseph;Arun' => ['', 'James', 'Joseph', 'Arun']
'James;Joseph;;;' => ['James', 'Joseph']
';;;' => ['']
>>> test_solution(lambda s: (s[:-1] if s.endswith(';') else s).split(';'))
'James;Joseph;Arun;' => ['James', 'Joseph', 'Arun']
'James;;Arun' => ['James', '', 'Arun']
'James;Joseph;Arun' => ['James', 'Joseph', 'Arun']
';James;Joseph;Arun' => ['', 'James', 'Joseph', 'Arun']
'James;Joseph;;;' => ['James', 'Joseph', '', '']
';;;' => ['', '', '']
に変数名として 'str'を使用しないでくださいを。これは組み込みの 'str'を隠します。 –
@ Mark Byersご意見ありがとうございます。私の実際のvar名は異なります。 – Jisson