在python中,将字符串放在字符串旁边

2024-09-30 01:33:17 发布

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

我有一长串的选择题,像这样:

8. OVERT    (R.R.B. 1996)
(a) Deep    (b) Shallow
(c) Secret  (d) Unwritten
9. ACCORD   (Railways, 1991)
(a) Solution    (b) Act
(c) Dissent     (d) Concord

我想把这个选项[(a)(b)(c)(d)]放在问题旁边,有这样一个标签:

8. OVERT    (R.R.B. 1996)   (a) Deep    (b) Shallow (c) Secret  (d) Unwritten
9. ACCORD   (Railways, 1991)    (a) Solution    (b) Act (c) Dissent     (d) Concord

我在(a)之前使用了"\b",如下所示:

newString = QuestionString.replace("(a)", "\b(a)")

但是这只删除了(a)前面的一些空格。但是我想删除它前面的换行符。有人能建议我如何使用python删除它吗


Tags: secret选项标签act选择题solutiondeepconcord
3条回答

试一试


string = """8. OVERT    (R.R.B. 1996)
(a) Deep    (b) Shallow
(c) Secret  (d) Unwritten
9. ACCORD   (Railways, 1991)
(a) Solution    (b) Act
(c) Dissent     (d) Concord"""
string = string.replace("\n(a)", "\t(a)")
string = string.replace("\n(c)", "\t(c)")

print(string)
>>> 8. OVERT    (R.R.B. 1996)       (a) Deep    (b) Shallow (c) Secret  (d) Unwritten
9. ACCORD   (Railways, 1991)    (a) Solution    (b) Act (c) Dissent     (d) Concord
`` `

您可以使用正则表达式:

\n(\([a-z]\).+)

并将其替换为

\1\t

a demo on regex101.com

您可以尝试使用以下模式替换正则表达式:

\r?\n(?!\d+\.)

这将针对所有而非的CR?LF,然后是一个数字点线,该点线开始下一节。将替换字符串设为空,以删除此类匹配的CR?LF

inp = """8. OVERT    (R.R.B. 1996)
(a) Deep    (b) Shallow
(c) Secret  (d) Unwritten
9. ACCORD   (Railways, 1991)
(a) Solution    (b) Act
(c) Dissent     (d) Concord"""
output = re.sub(r'\r?\n(?!\d+\.)', '', inp)
print(output)

这张照片是:

8. OVERT    (R.R.B. 1996)(a) Deep    (b) Shallow(c) Secret  (d) Unwritten
9. ACCORD   (Railways, 1991)(a) Solution    (b) Act(c) Dissent     (d) Concord

相关问题 更多 >

    热门问题