Python 如果字符串只包含可镜像的字母,则将其反转

Python 如果字符串只包含可镜像的字母,则将其反转,python,string,Python,String,问题是。不,这不是家庭作业,这是自学的 我试图回答以下问题: 弦誓言的镜像是弦wov,镜像木头是弦boow。但是,字符串床的镜像不能表示为字符串,因为e的镜像不是有效字符。 镜像为有效字符的字母表中的字符有:b、d、i、o、v、w和x。开发函数mirror(),该函数接受字符串并返回其镜像,但前提是镜像可以用字母表中的字母表示 **我的代码** def mirror(word): '''returns mirror image of word but if it can be repre

问题是。不,这不是家庭作业,这是自学的

我试图回答以下问题:

弦誓言的镜像是弦wov,镜像木头是弦boow。但是,字符串床的镜像不能表示为字符串,因为e的镜像不是有效字符。 镜像为有效字符的字母表中的字符有:b、d、i、o、v、w和x。开发函数mirror(),该函数接受字符串并返回其镜像,但前提是镜像可以用字母表中的字母表示

**我的代码**

def mirror(word):
    '''returns mirror image of word but if it can be represented
       using letters in the alphabet'''
    for i in range (0,len(word)):
        if i == 'bdiovwx':
            print(str(word.reverse))
        else:
            print ('NOPE')
我得到的结果是什么都没有。就像在我执行程序时一样,没有打印任何内容

有什么想法吗


谢谢

这不需要for循环。本质上,您正在测试单词的所有字符是否属于
'bdiovwx'
中的一个字符,因此,您可以精确地检查-word中字符集之间的子集关系,以及
'bdiovwx'

另外,字符串在python中没有反向方法,因此可以使用技巧
“string”[::-1]
打印其反向

def mirror(word):
    '''
    returns mirror image of word but if it can be represented
    using letters in the alphabet
    '''
    if set(word).issubset(set('bdiovwx')):
        print(word[::-1])
    else:
        print ('NOPE')

这不需要for循环。本质上,您正在测试单词的所有字符是否属于
'bdiovwx'
中的一个字符,因此,您可以精确地检查-word中字符集之间的子集关系,以及
'bdiovwx'

另外,字符串在python中没有反向方法,因此可以使用技巧
“string”[::-1]
打印其反向

def mirror(word):
    '''
    returns mirror image of word but if it can be represented
    using letters in the alphabet
    '''
    if set(word).issubset(set('bdiovwx')):
        print(word[::-1])
    else:
        print ('NOPE')

请注意,“d”反映了“b”,而“b”反映了镜像中的“d”:


请注意,“d”反映了“b”,而“b”反映了镜像中的“d”:


通过修正算法,您可以得到结果。您只需循环遍历这些项,添加所有要设置的元素,并在以后进行比较,如果它包含在u定义的字母表集中,
'bdiovwx'
notFound
用于在发现不属于u定义的接受集的变量时停止迭代
'bdiovwx'

word[:-1]
生成反向的单词

def mirror(word):
    '''returns mirror image of word but if it can be represented
       using letters in the alphabet'''
    i,notFound=0,True
    D=set()
    while notFound and i < len(list(word)):
        if word[i] not in list('bdiovwx'):
            notFound= False
        D.add(word[i])
        i+=1
    if notFound and D.issubset(set(list('bdiovwx'))):
        print word[::-1]
    else:
        print ('NOPE')

通过修正算法,您可以得到结果。您只需循环遍历这些项,添加所有要设置的元素,并在以后进行比较,如果它包含在u定义的字母表集中,
'bdiovwx'
notFound
用于在发现不属于u定义的接受集的变量时停止迭代
'bdiovwx'

word[:-1]
生成反向的单词

def mirror(word):
    '''returns mirror image of word but if it can be represented
       using letters in the alphabet'''
    i,notFound=0,True
    D=set()
    while notFound and i < len(list(word)):
        if word[i] not in list('bdiovwx'):
            notFound= False
        D.add(word[i])
        i+=1
    if notFound and D.issubset(set(list('bdiovwx'))):
        print word[::-1]
    else:
        print ('NOPE')

你能把它打印出来吗?根据你的代码,它应该打印出和字母一样多的“否”。如果你的问题得到解决,别忘了接受下面的一个答案。你能让它打印一些东西吗?根据你的代码,它应该打印出和字母一样多的“否”。如果你的问题得到解决,别忘了接受下面的一个答案。