【问题标题】:If condition with startswith and endswith error如果条件以开头和结尾为错误
【发布时间】:2019-07-18 09:34:03
【问题描述】:

我拆分了从 ( 到 ) 开始的数据 x 包含的数据喜欢 (33)Knoxville, TN,,,(1)Basking Ridge, NJ location = "".join(x.split("()"))[4:] 在这个拆分逻辑中我应该给出什么条件 [3:] ??

           if name:

        if x.startswith('(') and x.endswith(')'):

            location = "".join(x.split("()"))[3:]

            print(location)
        else:
            location = x

【问题讨论】:

  • 你有两次endswith(),但你没有使用startswith()
  • 请考虑在您的问题中正确格式化代码,并且不要忘记发布错误回溯,正如@furas 所说。
  • split("()") 不会在 "("")" 上拆分,而只会在 "()" 上拆分
  • re.split(r'[()]', strin) 将在 () 上进行拆分
  • 编辑您的数据,使其更具可读性并显示预期结果。

标签: python startswith ends-with


【解决方案1】:

希望您尝试通过(chars), 进行拆分,

>>> s = '(1)Basking Ridge, NJ (33)Knoxville, TN'
>>> import re
>>> re.split(r'\s*\([^()]*\)\s*|\s*,\s*', s)
['', 'Basking Ridge', 'NJ', 'Knoxville', 'TN']
>>> t = re.split(r'\s*\([^()]*\)\s*|\s*,\s*', s)
>>> ','.join([i for i in t if i])
'Basking Ridge,NJ,Knoxville,TN'
>>> 

【讨论】:

  • 像我一样在最后加入。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-27
  • 1970-01-01
  • 2018-07-02
  • 1970-01-01
  • 2019-12-02
  • 1970-01-01
相关资源
最近更新 更多