如何找到字符的位置并在Python中以相反的顺序列出位置?

时间:2014-10-26 02:45:12

标签: python python-2.7

如何在python中获取字符串中字符的位置,并按相反的顺序列出位置?另外,如何让它在字符串中查找大写和小写字符?

例如:如果我放入AvaCdefh,我会寻找' a' (包括大写和小写),并在我的初始字符串中返回a的位置。在这个例子中,' a'位于0和2位置,所以如何让python将其返回为' 2 0' (有空间)?

2 个答案:

答案 0 :(得分:1)

使用re模块很容易实现:

import re
x = "AvaCdefh"
" ".join([str(m.start()) for m in re.finditer("[Aa]",x)][::-1])

......产生:

'2 0'

在使用How can I reverse a list in python?的第二个答案中描述的方法构造字符串之前,列表是相反的。

答案 1 :(得分:1)

您可以使用string.index()查找第一个字符。

w= "AvaCdefh"

将字符串更改为大写

print w.upper() #Output: AVACDEFH

将字符串更改为小写

print w.lower() #Output: avacdefh

使用python内置函数找到第一个charchter:

print w.lower().index('a') #Output: 0

print w.index('a') #Output: 2

翻转单词

print w[::-1] #Output: hfedCavA

但你可以使用理解列表来做到这一点:

char='a'
# Finding a character in the word
findChar= [(c,index) for index,c in enumerate(list(w.lower())) if char==c ]
# Finding a character in the reversed word 
inverseFindChar = [(c,index) for index,c in enumerate(list(w[::-1].lower())) if char==c ]


print findChar  #Output: [('a', 0), ('a', 2)]
print inverseFindChar #Output: [('a', 5), ('a', 7)]

使用lambda的另一种方法。

l = [index for index,c in enumerate(list(w.lower())) if char==c ]
ll= map(lambda x:w[x], l)
print ll #Output: ['A', 'a']

然后,您可以将其作为函数包装:

def findChar(char):
    return " ".join([str(index) for index,c in enumerate(list(w.lower())) if char==c ])

def findCharInReversedWord(char):
    return " ".join([str(index) for index,c in enumerate(list(w[::-1].lower())) if char==c ])
print findChar('a')
print findChar('c')

print findCharInReversedWord('a')
相关问题