字符串的endswith()函数给出矛盾的结果

时间:2019-04-12 11:08:15

标签: python

当我注意到四个简单的一行语句的四个结果时,我只是在Python控制台中鬼混:

1. "x".endswith("") True

2. "x".endswith("x") True

然后,当它们给我这些结果时,我试图从语句中去除空格:

3. "x".strip().endswith("") True

4. "x".strip().endswith("x") True

如何将所有结果都设为True?字符串函数如何返回True"x"""结尾?这不是矛盾的,还是我在这里错过了什么?

Windows 10上PyCharm上的Python 2.7。

2 个答案:

答案 0 :(得分:0)

class Inspector < ActionDispatch::Routing::RoutesInspector def collect_all_routes res = collect_routes(@routes) @engines.each do |engine_name, engine_routes| res += engine_routes.map{|er| er.merge({ engine_name: engine_name }) } end res end def collect_routes(routes) routes.collect do |route| ActionDispatch::Routing::RouteWrapper.new(route) end.reject do |route| route.internal? end.collect do |route| collect_engine_routes(route) { name: route.name, verb: route.verb, path: route.path, reqs: route.reqs, original: route, } end end res = Inspector.new(Rails.application.routes.routes.routes).collect_all_routes 函数删除被调用字符串的开头和结尾的所有空格。您的字符串.strip()周围没有空格,因此不会有任何变化(您可以通过运行"x"进行检查。

您还正在检查它是否以空字符串结尾,Python中的每个字符串都这样做!

在您的字符串中添加一些空格(例如"x" == "x".strip()),并在您的"x "调用(例如endswith)中使用空格字符,以更好地了解{{1 }}函数起作用。

答案 1 :(得分:-1)

如果要检查字符串是否以空格结尾,请尝试"x "

例如,"x ".endswith(" ")返回True,但是"x ".strip().endswith(" ")返回False

""是一个空字符,您尝试执行的操作无效。空格字符显示为:" "