简体   繁体   中英

How to find the position of a character and list the position in reverse order in Python?

How can I get the position of a character inside a string in python, and list the position in reverse order? Also how can I make it look for both uppercase and lowercase character in the string?

eg: if I put in AvaCdefh, and I look for 'a' (both uppercase and lowercase), and return the position for a in my initial string. In this example 'a' is located in 0 and 2 position, so how can I make python to return it as '2 0' (with space)?

This is easily achieved using the re module:

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

... which produces:

'2 0'

The list is reversed before constructing the string using the method described in the second answer to How can I reverse a list in python? .

You can use string.index() to find the first character.

w= "AvaCdefh"

To change string to upper case

print w.upper() #Output: AVACDEFH

To change string to lower case

print w.lower() #Output: avacdefh

To find the first charchter using python built-in function:

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

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

To reverse a word

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

But you can do this using comprehension list:

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)]

The other way to do it using 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']

Then, you can wrap this as a function:

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')

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