teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

stripの適用順序を変更

2020/10/14 11:33

投稿

Daregada
Daregada

スコア11990

answer CHANGED
@@ -1,15 +1,20 @@
1
1
  おそらく、質問者がやりたいことは、「文字列に含まれる単語と、あらかじめ指定した単語リスト中の単語が、完全一致するものを見つけたい」ということですよね。
2
2
 
3
- - 文字列の両端から邪魔な文字を`strip`で取り除いてから、`split`で単語に分割
3
+ - 文字列を`split`で単語に分割してから、各単語の両端邪魔な文字を`strip`で取り除
4
4
  - 分割された単語の中に、あらかじめ指定した単語リストの要素が含まれればそれを表示
5
5
 
6
6
  ```Python
7
7
  text = "The T-shirt looks cool."
8
8
  words = ['T', 'shirt', 'cool', 'l']
9
9
 
10
- splitted = text.strip(' .,').split()
10
+ splitted = list(map(lambda x: x.strip(' .,!?'), text.split()))
11
11
  print(splitted)
12
12
  for word in words:
13
13
  if word in splitted:
14
14
  print(word)
15
+ ```
16
+
17
+ ```result
18
+ ['The', 'T-shirt', 'looks', 'cool']
19
+ cool
15
20
  ```