繁体   English   中英

在Python中分隔字符串和整数

[英]Separate strings and integers in Python

我想分割字符串和数字。 因此,如果连接的字符串是:

Hans went to house number 10 92384 29349

它应该将文本分成:

Hans went to house number | 10 | 92384 | 29349

我很困惑如何解决这个问题,因为拆分不会起作用,因为它也会分裂Hans | 去了 到| 房子| 数..

正则表达式非常简单:

>>> import re
>>> s = "Hans went to house number 10 92384 29349"
>>> re.split(r'\s+(?=\d+\b)', s)
['Hans went to house number', '10', '92384', '29349']

如果你想添加| ,那说你的问题很混乱 char到输出,只需再次加入输出:

>>> ' | '.join(_)
'Hans went to house number | 10 | 92384 | 29349'

如果你的目标是实现一个可以解决问题的函数,你可以这样写:

def split_numbers(string, join=None):
   from re import split
   split = re.split(r'\s+(?=\d+\b)', string)
   return join.join(split) if join else split

请注意,我在我的正则表达式中添加了单词boundary \\b ,以避免匹配单词开头的2cups ,如句子中的2cups Hans went to house number 10 92384 29349 and drank 2cups of coffee

如果你只想添加| 到字符串,你可以试试这个:

a="Hans went to house number 10 92384 29349"

print(" ".join("| "+i if i.isdigit() else i for i in a.split()))

输出:

Hans went to house number | 10 | 92384 | 29349

您可以将句子拆分为单词,然后尝试将单词转换为整数。 如果演员表失败,那么只是连续

a = "Hans went to house number 10 92384 29349"
res = ""
for word in a.split():
   try:
      number = int(word)
      res += " | %d" % number
   except ValueError:
      res += " %s" % word

编辑:我试图给出“最简单”的解决方案。 我的意思是,它更长,但我想更容易理解。 不过,如果你了解其他解决方案(1行),那就去吧。

使用正则表达式拆分re

import re


txt = 'Hans went to house number 10 92384 29349'

' | '.join(re.split('\s(?=\d)',txt))

# 'Hans went to house number | 10 | 92384 | 29349'

您可以这样做:

a = 'Hans went to house number 10 92384 29349'

result = [' '.join([item for item in a.split(' ') if not item.isdigit()])] + [int(item) for item in a.split(' ') if item.isdigit()]

如果您想显示输出:

new_result = ' | '.join([str(item) for item in result])

你可以这样做:

a = "Hans went to house number 10 92384 29349"

res = []

for item in a.split():
    if item.isdigit():
        res.extend(['|', item])
    else:
        res.append(item)

print(' '.join(res))
#Hans went to house number | 10 | 92384 | 29349

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM