如何在python中连接字符串以获得多行文本,以便\n表示新行而不是字符?

2024-05-19 08:57:23 发布

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

给定一个字符串列表:['string_a', 'string_b', 'string_c']

如果我用\n连接这些字符串:

'\n'.join(['string_a', 'string_b', 'string_c'])

结果是(情况0):'string_a\nstring_b\nstring_c'

如果我打印结果(案例1):

string_a
string_b
string_c

假设我想用regex找到包含字符串b及其下的所有内容的行,但我找到的是:https://regex101.com/r/yF4u2I/1

正则表达式r'string_b\n.+'可以在案例1中找到文本,但在案例0中找不到文本。你知道吗

但是如果我把regex改成r'string_b\\n.+',它只会在大小写0中找到文本。这是因为\n被认为是字符而不是换行符。你知道吗

如何连接字符串列表以获得多行字符串?或者用regex找到它的另一种方法是什么?你知道吗


Tags: 字符串https文本com内容列表string情况
3条回答
l=['a','s','c']

''.join(list(i+'\n' for i in l )))

这很有效

您可以使用“|”表示左右:

r'string_b\n.+|string_b.+'

希望这有帮助!你知道吗

不要对regex字符串使用r前缀。r告诉regex将模式视为原始字符串。你知道吗

使用'string\u b\n.+'

Unless an 'r' or 'R' prefix is present, escape sequences in strings are interpreted according to rules similar to those used by Standard C. The recognized escape sequences are:

Escape Sequence Meaning Notes \newline Ignored \ Backslash () \' Single quote (') \" Double quote (") \a
ASCII Bell (BEL) \b ASCII Backspace (BS) \f ASCII Formfeed (FF) \n ASCII Linefeed (LF) \N{name} Character named name in the Unicode database (Unicode only) \r ASCII Carriage Return (CR) \t ASCII Horizontal Tab (TAB) \uxxxx Character with 16-bit hex value xxxx (Unicode only) \Uxxxxxxxx Character with 32-bit hex value xxxxxxxx (Unicode only) \v ASCII Vertical Tab (VT) \ooo Character with octal value ooo \xhh Character with hex value hh

相关问题 更多 >

    热门问题