ユーザーに文字列の入力を求めるプログラムをPythonで作成する必要があり、「s」または「S」で始まる単語のみを出力します。関数を使用し.split
て単語のリストを作成しています。ただし、「s」または「S」で始まる単語をPythonに認識させる方法を理解するのに苦労しています。どんな提案や助けも大歓迎です!
5 に答える
2
string のメソッドは、string をすべて小文字に変換するメソッドとstartswith
組み合わせて使用できます。lower
words = raw_input().split()
for word in words:
if word.lower().startswith('s'):
# do something
このメソッドstartswith
は、呼び出し文字列が引数として渡した部分文字列で始まる場合にのみ True を返します。
于 2013-10-17T00:59:45.607 に答える
1
@iCodez の素晴らしい例の文字列を借りる - ここに正規表現のアプローチがあります:
>>> import re
>>> mystr = 'Super Sally rode a super ship.'
>>> re.findall(r's\S+', mystr, flags=re.I)
['Super', 'Sally', 'super', 'ship.']
これにより、文字列を分割し、比較のために大文字と小文字を明示的に正規化する必要がなくなります。
また、不要な句読点をキャプチャしないように微調整することもできます。
>>> re.findall(r's\w+', mystr, flags=re.I)
['Super', 'Sally', 'super', 'ship']
于 2013-10-17T01:02:02.910 に答える
0
使用startswith
( http://docs.python.org/2/library/stdtypes.html#str.startswith )
for x in your_string.split():
if x.upper().startswith('S'):
print x
于 2013-10-17T00:58:29.573 に答える
0
startswith
実際にはタプルを取ります。
そう:
words = raw_input()
print [word for word in words.split() if word.startswith(('s', 'S'))]
英語によく似ていて、読みやすいです。私はそれを好むだろう.lower()
于 2013-10-17T08:40:55.867 に答える