简体   繁体   中英

How to remove brackets from output (i.e. [ ]) and other

I am having trouble getting the right output out for my code(for school).
st = input string
ch = input character(this is for python to search for ch in st)
The code find the both uppercase and the lowercase of the character that I put in for ch, and shows their position in the output(in reverse order).
So, I typed this code in

def whichPositionsRev (st, ch):
    if ch in st:
        inverseFindChar = [index for index,char in enumerate(list(st)) if char==ch ]
        return "Yes..." + str(inverseFindChar[::-1])
    else:
        return "No"

I am suppose to get 'Yes...8 5 2 ' as a return value(if I typed in 'abXabXabX' for st and 'X' for ch), but I'm keep getting 'Yes...[8, 5, 2]' as an output. I want to know which part code is causing it to put in brackets and commas in the return output?

Because you're calling str() on an array, you are getting the string representation of the array.

Replace

str(inverseFindChar[::-1])

with

" ".join(str(x) for x in inverseFindChar[::-1])

The part you're asking about is the str() function call. Python puts brackets and commas in the output for you to make it easier to see the array elements.

If you want to get the array elements separated by spaces, use

" ".join(map(str, inverseFindChar[::-1]))

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