Placing string beside a string in python

Viewed 65

I have a very long String of multiple choice questions like this:

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

I want to place this options [(a)(b)(c)(d)] beside the question with a tab like this :

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

I've used "\b" before the (a) like this:

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

But this only removes some spaces before the (a).But I want to remove the line break before it.Can someone suggest me how can I get rid of it using python ?

4 Answers

Try


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
`` `

You may try doing a regex replacement on the following pattern:

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

This will target all CR?LF which are not followed by a digit-dot line which starts the next section. Make the replacement empty string, to remove such matching 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)

This prints:

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

Se below, it is also OS indepenndent, notice the os.linesep

import os
longStr = """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"""

print(longStr)
longStr = longStr.replace(os.linesep +"(", " (")
print("")
print(longStr)
Related