简体   繁体   中英

Need to print only once outside the for loop

I am trying to print "True" if the input string has two consecutive identical letters. Foe ex: a="Matthew".For this input it should print True since the word 'Matthew' has two consecutive identical letters ("t"). Similarly print False for the word "John" since it has no consecutive letters.

Code:

 a="Matthew"

 for i in range(len(a)-1):
    if a[i]==a[i+1]:
       print("True")
    else:
       print("False")

Output: False, False, True, False, False, False

Just needed to print only once "True" if there are consequtive letters and needed to print only once "False" if there are no consequtive letters.

use an other variable

a="Matthew"
double = False

for i in range(len(a)-1):
   if a[i]==a[i+1]:
      double = True
      break
print(double)

Just for posterity's sake, I thought you might find it interesting to know that regex offers a much more concise solution:

a = "Matthew"
if re.search(r'(.)\1', a) :
    print("MATCH")
else:
    print("NO MATCH")

Python has for-else loop. So, it can be done this way too:

a = "Matthew"

    for i in range(len(a)-1):
        if a[i]==a[i+1]:
          print("True")
          break
    else:
         print("False")

Output: True

The else part executes only when the for-loop has iterated through the range; any break in between will lead to skipping the execution of else part.

So, if the input were a="Mathew" , it will print false

>>> print(any(i == j for i, j in zip(a[:-1], a[1:])))
True
# i j
# - -
# M a  No match.
# a t  No match.
# t t  Match. Done.
# t h
# h e
# e w

Or a slightly more performant but more verbose version (of course the re.search method is faster still but requires an understanding of regular expressions):

c = a[0]
for c2 in a[1:]:
    if c == c2:
        print('True')
        break
    c = c2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM