gpt4 book ai didi

python - 加入正则表达式搜索的输出

转载 作者:太空狗 更新时间:2023-10-30 01:18:12 25 4
gpt4 key购买 nike

  • 我有一个在文件中查找数字的正则表达式。
  • 我把结果放在一个列表中

问题在于它会为它找到的每个数字在一个新行上打印每个结果。它也忽略了我创建的列表。

我想做的是将所有数字放入一个列表中。我使用了 join() 但它不起作用。

代码:

def readfile():
regex = re.compile('\d+')
for num in regex.findall(open('/path/to/file').read()):
lst = [num]
jn = ''.join(lst)
print(jn)

输出:

122
34
764

最佳答案

出了什么问题:

# this iterates the single numbers you find - one by one
for num in regex.findall(open('/path/to/file').read()):
lst = [num] # this puts one number back into a new list
jn = ''.join(lst) # this gets the number back out of the new list
print(jn) # this prints one number

修复它:

阅读 re.findall() show's you,它已经返回了一个列表。

没有(太多)需要使用 for 来打印它。

如果你想要一个列表 - 只需使用 re.findall() 的返回值 - 如果你想打印它,使用 Printing an int list in a single line python3 中的方法之一(SO 上还有几篇关于打印的帖子在一行中):

import re

my_r = re.compile(r'\d+') # define pattern as raw-string

numbers = my_r.findall("123 456 789") # get the list

print(numbers)

# different methods to print a list on one line
# adjust sep / end to fit your needs
print( *numbers, sep=", ") # print #1

for n in numbers[:-1]: # print #2
print(n, end = ", ")
print(numbers[-1])

print(', '.join(numbers)) # print #3

输出:

['123', '456', '789']   # list of found strings that are numbers
123, 456, 789
123, 456, 789
123, 456, 789

独库:


更多关于一行打印:

关于python - 加入正则表达式搜索的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53994798/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com