【问题标题】:Reading a text until matched string and print it as a single line读取文本直到匹配字符串并将其打印为单行
【发布时间】:2020-11-29 11:48:13
【问题描述】:

我正在尝试以 python 初学者的身份编写程序。 此函数扫描给定的文本。每当我遇到符号“@、&、% 或 $”时,我必须将文本提取到该点并将其打印为单行。另外,我必须跳过符号,从符号后面的字母开始下一行并打印它,直到遇到另一个符号。 我希望我说得好。

symbols= "@, &, %, $”"
for symbol in text:
     if text.startswith (symbols):
        print (text)

我知道这不正确,但我只能这么想。任何帮助表示赞赏。

【问题讨论】:

标签: python


【解决方案1】:

IIUC,你需要用每个分隔符来分割字符串,所以你可以这样做:

symbols = "@, &, %, $".split(', ')
print(symbols)  # this is a list

text = "The first @ The second & and here you have % and finally $"

# make a copy of text
replaced = text[:]

# unify delimiters
for symbol in symbols:
    replaced = replaced.replace(symbol, '@')

print(replaced)  # now the string only have @ in the place of other symbols

for chunk in replaced.split('@'):
    if chunk:  # avoid printing empty strings
        print(chunk)

输出

['@', '&', '%', '$']  # print(symbols)
The first @ The second @ and here you have @ and finally @  # print(replaced)
The first 
 The second 
 and here you have 
 and finally 

第一步:

symbols = "@, &, %, $".split(', ')
print(symbols)  # this is a list

将您的字符串转换为列表。第二步使用replace 替换所有符号,因为str.split 仅适用于单个字符串:

# unify delimiters
for symbol in symbols:
    replaced = replaced.replace(symbol, '@') 

第三步也是最后一步是按所选符号(即@)分割字符串:

for chunk in replaced.split('@'):
    if chunk:  # avoid printing empty strings
        print(chunk)

【讨论】:

  • 谢谢!这就是我想要做的。祝你有美好的一天:)) @DaniMesejo
【解决方案2】:

如果我按照字面上给您的说明进行操作,我相信它不会比将文本中的这 4 个特殊字符中的每一个都替换为换行符更好:

text = """This is a line with @ and & in it.
This line has % and $ in it.
This line has nothing intersting in it.
This line has just @ in it.
The end.
"""
text = text.replace('@', '\n').replace('&', '\n').replace('%', '\n').replace('$', '\n')
print(text)

打印:

This is a line with 
 and 
 in it.
This line has 
 and 
 in it.
This line has nothing intersting in it.
This line has just 
 in it.

【讨论】:

    猜你喜欢
    • 2018-10-23
    • 2015-05-18
    • 2016-10-23
    • 2018-04-09
    • 2012-06-21
    • 2019-11-02
    • 2019-01-29
    • 1970-01-01
    • 2014-10-11
    相关资源
    最近更新 更多