0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Python 文字列の操作

Posted at

特定の文字をカウント

文字列中の特定の1文字を探す場合。

count1.py
tokyo = 'toukyoutokkyokyokakakyokukyokakyokutyou'
print(tokyo.count('t')) #=> 3
print(tokyo.count('k')) #=> 12
print(tokyo.count('y')) #=> 7
print(tokyo.count('ky')) #=> 6
print(tokyo.count('kyo')) #=> 6
print(tokyo.count('kyou')) #=> 1

文字列から複数種類の文字が合計いくつ含まれているか探す場合。

count2.py
tokyo = 'toukyoutokkyokyokakakyokukyokakyokutyou'
num = 0
for i in range(len(tokyo)):
    if('tky'.count(tokyo[i]) == 1):
        num+=1
print(num) #=> 22

文字列の中の特定の複数種の文字の内、連続したものの最大長。

count3.py
tokyo = 'toukyoutokkyokyokakakyokukyokakyokutyou'
num = 0
for i in range(len(tokyo)):
    for j in range(i, len(tokyo)):
        if all('tky'.count(a) == 1 for a in tokyo[i : j + 1]):
            num = max(num, j - i + 1)
print(num) #=> 3

all_ドキュメント
https://docs.python.org/ja/3/library/functions.html#all

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?