【问题标题】:split string by asterisk python用星号python分割字符串
【发布时间】:2013-04-03 09:24:31
【问题描述】:

我2天前刚开始学习python,如果我犯了明显的错误,请见谅

strings: "brake  break  at * time" --> ["at","time"]
"strang  strange  I felt very *" --> ["very",""]

我想在 * 之前和之后得到消息

我的尝试:

re.match(r"(?P(first_word)\w+) ('_*_') (?P(first_word)\w+)",strings).group('first_word')

获取第一个单词

re.match(r"(?P(first_word)\w+) ('_*_') (?P(first_word)\w+)",strings).group('last_word')

最后一个字

错误:无需重复

【问题讨论】:

  • 你试过.split('*'),因为它是你不想要的*

标签: python string pattern-matching matching split


【解决方案1】:

只需使用string.split('*')

像这样(仅适用于 1 *):

>>> s = "brake  break  at * time"
>>> def my_func(s):
     parts = s.split('*')
     a = parts[0].split()[-1]
     b = parts[1].split()[0] if parts[1].split() else ''
     return a,b
>>> my_func(s)
('at', ' time')

或者如果你想要正则表达式:

>>> s = "brake  break  at * time 123 * blah"
>>> regex = re.compile("(\w+)\s+\*\s*(\w*)")
# Run findall
>>> regex.findall(s)
[(u'at', u'time'), (u'123', u'blah')]

【讨论】:

  • 是的,输出正是我想要的!谢谢一百万!
  • 这个例子不适用"strang strange I felt very *" --> ["very",""]
  • 你的第一个例子不适用于s = "brake break at * time foo"
  • @Schoolboy 不。 >>> s="strang strange I felt very *" >>> s.split('*')[0].split()[-1],s.split('*')[1].split()[0] Traceback (most recent call last): File "<pyshell#70>", line 1, in <module> s.split('*')[0].split()[-1],s.split('*')[1].split()[0] IndexError: list index out of range
【解决方案2】:
import re
text1 = "brake  break  at * time"
text2 = "strang  strange  I felt very *"
compiled = re.compile(r'''
(\w+)  # one or more characters from [_0-9a-zA-Z] saved in group 1
\s+  # one or more spaces
\*  # literal *
\s*  # zero or more spaces
(\w*)  # zero or more characters from [_0-9a-zA-Z] saved in group 2
''',re.VERBOSE)

def parse(text):
    result = compiled.search(text)
    return [result.group(1), result.group(2)]

print(parse(text1))
print(parse(text2))

输出:

['at', 'time']
['very', '']

【讨论】:

    【解决方案3】:

    试试:

    [x.strip() for x in "test1 * test2".split('*', 1)]
    

    .strip() 去掉空格,.split('*', 1) 用星号分割字符串一次。

    你只要一个字:

    words = [x.strip() for x in "test1 * test2".split('*', 1)]
    first = words[0].rsplit(' ', 1)[1]
    last = words[1].split(' ', 1)[0]
    

    【讨论】:

    • 虽然它没有给出确切的输出但感谢您的帮助!
    • @PiotrHajduga 我更喜欢这个,因为它不使用正则表达式
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-26
    • 1970-01-01
    • 2020-11-18
    • 2015-05-31
    • 2017-05-18
    • 2020-08-30
    • 1970-01-01
    相关资源
    最近更新 更多