[英]how to print a name using .find
地點名稱
我需要希臘才能成為希臘
問題是這樣的:
position = location.find(":")
.find()
在未找到該事物時返回-1
,就像您的“GREECE”條目一樣。 你的下一行,
region_split = location[:position]
將字符串切片到該索引,但不包括該索引。 由於索引-1
指的是字符串的最后一個字符,因此它需要除最后一個字符之外的所有字符。
最簡單的解決方案是放入一個特殊情況:
position = location.find(":")
region_split = location[:position] if position >= 0 else location[:]
但更有趣的方法是使用模數:
position = location.find(":") % (len(location) + 1)
region_split = location[:position]
如果找到':'
則不會影響position
(因為它總是小於len(location)
,但如果找不到':'
,則-1 % len(location) + 1
精確計算字符串的長度location
,因此無論如何您都可以使用以下切片捕獲整個字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.