【问题标题】:How can i include the separator when calling split()调用 split() 时如何包含分隔符
【发布时间】:2020-04-20 18:22:41
【问题描述】:

我有一个电话号码列表,如下所示:

numbers=[
‘(080)3453421256’,
‘(04256)6679345390’,
‘(022)1135643320‘]

我必须得到那些具有不同长度的数字的前缀。 numbers.split(‘)’, 0) 给出不带括号的输出。 如何包含括号并获取前缀?

【问题讨论】:

  • 为什么不在拆分后添加“)”?
  • 看起来您正在使用富文本引号。我建议使用纯 ascii 引号。
  • 你能举例说明你的预期输出吗?
  • 我的输出 —> (080 , (04256, (022 ; 预期输出 —> (080), (004256), (022))
  • 在一个解释级别上,您不能:根据定义,split 删除分隔符。你可以追加一个新的,但原来的已经不存在了。然而,regex 会很容易找到你想要的:“(d+)”——并且会毫不费力地返回匹配的字符串。另外,请注意您保留了括号方括号是表示列表的字符。

标签: python python-3.x string list split


【解决方案1】:

试试这个代码:

for i in numbers:
    a = i.split(")")
    s = a[0]
    print(s[0:]+")",end = ",")

或者试试这个:

for i in numbers:
    a = i.index(")")
    s = i[0:a+1]
    print(s,end = ", ")

输出:

(080),(04256),(022),

【讨论】:

  • 我想包括括号。我希望输出看起来像这样:(080),(04256),(022)
【解决方案2】:

使用 Python 的正则表达式包对您来说可能更简单:

import re

numbers=[
"(080)3453421256",
"(04256)6679345390",
"(022)1135643320"]

pattern = "\(\d+\)"    # L_PAREN, at least one digit, R_PAREN

for num in numbers:
    print(re.match(pattern, num).group())   # Your data has only one match in each line.

输出:

(080)
(04256)
(022)

【讨论】:

    猜你喜欢
    • 2019-06-19
    • 2014-02-24
    • 1970-01-01
    • 2013-02-01
    • 1970-01-01
    • 2022-06-28
    • 1970-01-01
    • 2014-03-18
    • 1970-01-01
    相关资源
    最近更新 更多