Koushik
Koushik

Reputation: 61

Placing string beside a string in python

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 ?

Upvotes: 2

Views: 82

Answers (4)

Marcel Preda
Marcel Preda

Reputation: 1205

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)

Upvotes: 0

Jan
Jan

Reputation: 43169

You could use a regular expression:

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

And replace this with

\1\t

See a demo on regex101.com.

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521178

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

Upvotes: 1

kabooya
kabooya

Reputation: 566

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

Upvotes: 2

Related Questions