-1

Pythonには、in文字列に部分文字列または文字が存在するかどうかを確認するために使用できる演算子があることを知っています。これを行うには、各文字列 (長さの部分文字列) をチェックします。以下のコードが唯一の方法ですか、それともこれを達成できる他の方法はありますか?

m = "college"
s = "col"
lm = len(m)
ls = len(s)
f = 0

for i in range(lm):    
    if (i+ls) <= lm:
        if s == m[i:(i+ls)]:            
            global f
            f = 1
            break
if f:
    print "present"
else:
    print "not present"

ここで行っているのは、部分文字列が のcol場合、プログラムは長さ部分文字列の文字列と部分文字列をチェックして、メイン文字列の最初から最後まで移動し、true かどうかを返します。

col
oll
lle
leg
ege                
4

4 に答える 4

1

You could try something like this:

In [1]: m = 'college'

In [2]: s = 'col'

In [3]: if any(m[i:i+len(s)] == s for i in range(len(m)-len(s)+1)):
   ...:     print 'Present'
   ...: else:
   ...:     print 'Not present'
   ...:     
Present

Where the any checks every substring of m of length len(s) and sees if it equals s. If so, it returns True and stops further processing (this is called 'short-circuiting' and is pretty similar to the break you have above).

Here is what the any piece would look like if we replaced it with a list comprehension and took out the equality comparison:

In [4]: [m[i:i+len(s)] for i in range(len(m)-len(s)+1)]
Out[4]: ['col', 'oll', 'lle', 'leg', 'ege']
于 2013-05-11T19:11:41.323 に答える
1

そこは必要ありませんglobal。また、できること

In [1]: %paste
m = "college"
s = "col"

In [2]: 'not ' * all(s != m[i:i+len(s)] for i in range(1+len(m)-len(s))) + 'present'
Out[2]: 'present'

しかし、実際にはもちろんs in m

于 2013-05-11T19:13:07.253 に答える