簡體   English   中英

比較Python中的字符

[英]Comparing characters in Python

是python的新手,並且每天都在研究單詞生成器。 我正在測試IE設置字長的限制,確保它至少有1個大寫,小寫和數字等。

import random

from string import ascii_uppercase, ascii_lowercase, ascii_letters, digits

pool = ascii_letters + digits
wordLen=random.randint(7,14)
answer = random.sample(pool, wordLen)

while True:
    if not any(char.isupper() for char in answer):
        answer[random.randrange(len(answer))] = random.choice(ascii_uppercase)
        continue

    if not any(char.islower() for char in answer):
        answer[random.randrange(len(answer))] = random.choice(ascii_lowercase)
        continue

     if not any(char.isdigit() for char in answer):
        answer[random.randrange(len(answer))] = random.choice(digits)
        continue

     break

answer = ''.join(answer)

我想添加一個進一步的限制-確保連續的字符不相同。 現在,我已經研究了字符串操作,但是根本找不到如何應用它。 讓我告訴你我研究過的有關字符串比較的一些知識

if stringx == stringy:
    print 'they are the same'
else
    print 'they are different'

我得到了實際的比較部分,但是我不知道如何使語句再次運行以再次生成另一個字符,而無視剛剛生成的那個字符。 任何建議,將不勝感激

要繼續使用any()結構,您需要像在itertools配方部分中所介紹的那樣引入成對的可迭代,然后可以執行以下操作:

import itertools

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = itertools.tee(iterable)
    next(b, None)
    return itertools.izip(a, b)

answer = "abcdeffghik"
if any( first_char == second_char for first_char, second_char in pairwise(answer)):
    print "Duplicates exists"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM