【发布时间】: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
我有一个字符串"@user hello world",我希望我分成"@user" 和"hello world"。每个子字符串的内容无关紧要,我只想将原始字符串分成第一个单词和其余部分。也可以将"a b c d e f" 转换为"a" 和"b c d e f"。怎么样?
【问题讨论】:
标签: python python-3.x string
str.split() 采用可选的第二个参数来表示最大拆分数。在这里,您只想拆分第一项以便使用:
s = "@user hello world"
a, b = s.split(' ', 1)
a, b
# ('@user', 'hello world')
【讨论】:
带有参数的拆分方法将完成这项工作。
test_str = "This is a sentence"
print(test_str.split(' ', 1 ))
【讨论】: