【问题标题】:How to correctly split with multiple underscores? [duplicate]如何正确拆分多个下划线? [复制]
【发布时间】:2019-01-23 22:22:02
【问题描述】:

我想知道当您有未知数量的下划线时如何正确拆分字符串。 我的输入如下所示:

One Two_________1.0 2.0 3.0
Three Four______4.0 5.0 6.0
Five Six________7.0 8.0 9.0

单词和数字之间有未知数量的下划线。我需要将此输入拆分为单词和数字。我尝试以这种方式使用split

details = input.split("_")
words = details[0]
numbers = details[1]

但是,它正确地只保存了单词。当我将输入更改为只有一个下划线时它起作用了,但是当它有多个下划线时我找不到解决方案。

【问题讨论】:

标签: python string


【解决方案1】:

您可以为此使用正则表达式。

import re
re.split('_+', 'asd___fad')
>>> ['asd', 'fad']

基本上,这是说“当你看到一个下划线(split 的第一个参数中的下划线)或更多(下划线后面的加号)时拆分”

【讨论】:

  • 谢谢,这完全解决了问题!这个解决方案很容易在我的程序中实现,并且易于使用。
【解决方案2】:

使用负索引。 IE。数字 = 详细信息[-1]

【讨论】:

  • 您也可以使用正则表达式(正则表达式),但是如果您不了解自己在做什么,这些实现起来可能会很复杂
【解决方案3】:

仅使用内置函数:

# slices input from beginning to first underscore
words = input[:input.find("_")]
# slices input from first underscore to the end, then replaces "_" with "".
numbers = input[input.find("_"):].replace("_", "")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-21
    • 2015-04-17
    • 2020-09-26
    相关资源
    最近更新 更多