【问题标题】:Python split, exclude a portion of the string [duplicate]Python拆分,排除字符串的一部分[重复]
【发布时间】:2021-02-10 13:17:03
【问题描述】:

这是给我的字符串Enter 3 random strings, separated by commas: The,Dave,Make

我希望列表仅包含以下内容:["The", "Dave", "Make"]

我尝试过使用拆分,但结果是错误

strings = input("Enter 3 random strings, separated by commas:")
strings = strings.split()

【问题讨论】:

  • 请展示您尝试过的内容,并说明您遇到的问题。谢谢。

标签: python python-3.x string list


【解决方案1】:

string.split()strip() 方法一起使用:

In [2680]: s = "Enter 3 random strings, separated by commas: The,Dave,Make"
In [2686]: s.split(':')[-1].strip().split(',')
Out[2686]: ['The', 'Dave', 'Make']

【讨论】:

  • 知道了,谢谢你的帮助!
  • @LimHanYang 为什么不接受我的回答?
  • 对不起,我错过了点击并接受了别人的回答
【解决方案2】:

试试这个:

string = 'Enter 3 random strings, separated by commas: The,Dave,Make'

lst = string.split(':')[-1].strip().split(',')

输出:

>>> lst
['The', 'Dave', 'Make']

【讨论】:

    【解决方案3】:

    在冒号处拆分字符串,删除多余的空格,然后在逗号处拆分。

    string = 'Enter 3 random strings, separated by commas: The,Dave,Make'
    result = string.split(':')[1].strip().split(',')
    

    【讨论】:

      【解决方案4】:

      如果字符串是从控制台获取的,它的第一部分应该是输入提示:

      strings = input("Enter 3 random strings, separated by commas:")
      strings = strings.strip().split(',')
      

      代码可以缩短为单行:

      strings = input("Enter 3 random strings, separated by commas:").strip().split(',')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-12
        • 1970-01-01
        • 2021-07-06
        • 2020-12-22
        • 2010-11-03
        • 1970-01-01
        相关资源
        最近更新 更多