简体   繁体   中英

how to print a name using .find

Location Name

I need Greec to be Greece

The problem is this:

position = location.find(":")

.find() returns -1 when the thing is not found, as is the case with your "GREECE" entry. Your next line,

region_split = location[:position]

slices the string up to, but not including, that index. Since index -1 refers to the last character of the string, it takes all but the last character.


The easiest solution would be to put in a special case:

position = location.find(":")
region_split = location[:position] if position >= 0 else location[:]

but a more fun way would be to use a modulo:

position = location.find(":") % (len(location) + 1)
region_split = location[:position]

which will not affect position if ':' is found (since it would always be less than len(location) , but if ':' is not found, -1 % len(location) + 1 evaluates to exactly the length of the string location , so you capture the whole string anyway with the following slice.

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