[英]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. .find()
在未找到该事物时返回-1
,就像您的“GREECE”条目一样。 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.由于索引
-1
指的是字符串的最后一个字符,因此它需要除最后一个字符之外的所有字符。
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.如果找到
':'
则不会影响position
(因为它总是小于len(location)
,但如果找不到':'
,则-1 % len(location) + 1
精确计算字符串的长度location
,因此无论如何您都可以使用以下切片捕获整个字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.