简体   繁体   中英

While Loop checking for letter within string in Python

I want to create a while-loop that loops until a random string has been created that starts with "A" and ends with "Z".

import string
from random import choice

def random_string():
    """ Generates a 5 letter random string. """
    rs = ''.join(choice(string.ascii_uppercase) for _ in range(5))
    print(rs)
    
    

while random_string()[-1] != "Z" and random_string()[0]) != "A":
    print("keep going")
return random_string
      

So far I have this and I am running into trouble with the while loop checking for the first and last letter. Is there a simpler (and correct) way to test this?

Thanks in advance.

If you want to have the first and last letters in your string to be the same, why not just randomize the middle 3 characters.

You would have a successful result every run.

pre = 'A'
suf = 'Z'
n = 3

result = pre + ''.join(random.choice(string.ascii_uppercase) for i in range(n)) + suf

#'ACUUZ'

Id you want to achieve this with the while loop, you need to ensure your return is outside of your loop, and that your loop runs whilst your condition is not met.

 def random_string():
    rs = ''.join(choice(string.ascii_uppercase) for _ in range(5))
    while rs[-1] != "Z" or rs[0] != "A":
        rs = ''.join(choice(string.ascii_uppercase) for _ in range(5))
    return rs

With the above, we define our return after the while loop, ensure it only returns when a match has been found.

Output

for i in range(10): 
    print(random_string())

ASKPZ
AHOKZ
AYWQZ
ASHYZ
ACENZ
ASIVZ
ADTVZ
AZWHZ
AAHHZ
AKZHZ

This should work as you intended.

import string
from random import choice
    
random_string = ''.join(choice(string.ascii_uppercase) for _ in range(5))

while random_string[-1] != "Z" or random_string[0] != "A":
    random_string = ''.join(choice(string.ascii_uppercase) for _ in range(5))
    print("keep going")

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