【问题标题】:Split string into first word and remaining text? [duplicate]将字符串拆分为第一个单词和剩余文本? [复制]
【发布时间】:2020-02-08 18:37:18
【问题描述】:

我有一个字符串"@user hello world",我希望我分成"@user" 和"hello world"。每个子字符串的内容无关紧要,我只想将原始字符串分成第一个单词和其余部分。也可以将"a b c d e f" 转换为"a" 和"b c d e f"。怎么样?

【问题讨论】:

    标签: python python-3.x string


    【解决方案1】:

    str.split() 采用可选的第二个参数来表示最大拆分数。在这里,您只想拆分第一项以便使用:

    s = "@user hello world"
    a, b = s.split(' ', 1)
    a, b
    # ('@user', 'hello world')
    

    【讨论】:

      【解决方案2】:

      带有参数的拆分方法将完成这项工作。

      test_str = "This is a sentence"
      print(test_str.split(' ', 1 ))
      

      【讨论】:

        猜你喜欢
        • 2022-06-20
        • 1970-01-01
        • 2022-01-18
        • 1970-01-01
        • 2011-06-12
        • 1970-01-01
        • 2017-04-26
        • 1970-01-01
        • 2019-01-11
        相关资源
        最近更新 更多