user12904074
user12904074

Reputation:

how we can build a special string from a list?

I have a list like this:

list=[' is ', ' the ', ' . ', ' .kda ', ...]

I am wondering how I can change this is like the following:

1- put | after each '

2- remove all ' except first and last

3- removing all ,

4-remove [ and ] from the begging and end of the list

5- change all . to \. even if it is not alone. for example changing u.s to u\.s

output:

list= is | the | \. | \.kda | ...

Upvotes: 1

Views: 57

Answers (3)

mrbTT
mrbTT

Reputation: 1409

list=[' is ', ' the ', ' . ', ' .kda ']
# add a r before the string declaration to specify it as a regex string
re_list = r"|".join(list).replace('.', '\.')
print(re_list)

#>>>' is | the |  \. |  \.kda | ...'

Upvotes: 1

Timur Shtatland
Timur Shtatland

Reputation: 12347

Use list comprehension and re.sub

import re
list = [' is ', ' the ', ' . ', ' .kda ']
s = '|'.join([re.sub(r'\.', '\.', x) for x in list])
print(s)
# is | the | \. | \.kda 

Upvotes: 2

I break things
I break things

Reputation: 326

String manipulation

answer = str(list).replace("'", "'|").replace(".", "\.").strip('[').strip(']')

Upvotes: 1

Related Questions