在Python中分离字符串和整数

2024-04-29 01:28:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把字符串和数字分开。因此,如果串联的字符串是:

Hans went to house number 10 92384 29349

应将文本分成:

^{pr2}$

我对如何处理这个问题感到困惑,因为分割是行不通的,因为它也会分裂汉斯去房子的号码。。在


Tags: to字符串文本number数字号码househans
3条回答

使用正则表达式非常简单:

>>> 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']

也就是说,您的问题令人困惑,如果要将|字符添加到输出,只需再次连接输出:

^{pr2}$

如果您的目标是实现一个能做到这一点的函数,您可以编写以下内容:

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

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

如果只想将|添加到字符串中,可以尝试以下操作:

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

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

输出:

^{pr2}$

你可以把你的句子分成单词,然后试着把这个单词转换成整数。如果演员失败了,那就用康卡

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行),那就去做吧。在

相关问题 更多 >