-1

I have this list of strings

lst = ["/foo/dir/c-.*.txt","/foo/dir2/d-.*.svc","/foo/dir3/es-.*.info"]

and I have a prefix string :

/root

Is there any pythonic way to add the prefix string to each element in the list, so the end result will look like this:

lst = ["/root/foo/dir/c-.*.txt","/root/foo/dir2/d-.*.svc","/root/foo/dir3/es-.*.info"]

If it can be done without iterating and creating new list ...

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
user63898
  • 29,839
  • 85
  • 272
  • 514

5 Answers5

2

used:

  1. List Comprehensions

List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.

  1. F=Strings

F-strings provide a way to embed expressions inside string literals, using a minimal syntax. It should be noted that an f-string is really an expression evaluated at run time, not a constant value. In Python source code, an f-string is a literal string, prefixed with 'f', which contains expressions inside braces. The expressions are replaced with their values.

lst = ["/foo/dir/c-.*.txt","/foo/dir2/d-.*.svc","/foo/dir3/es-.*.info"]
prefix = '/root'
lst =[ f'{prefix}{path}' for path in lst] 

print(lst)
Abhi
  • 995
  • 1
  • 8
  • 12
1

Use list comprehensions and string concatenation:

lst = ["/foo/dir/c-.*.txt","/foo/dir2/d-.*.svc","/foo/dir3/es-.*.info"]
   
print(['/root' + p for p in lst])

# ['/root/foo/dir/c-.*.txt', '/root/foo/dir2/d-.*.svc', '/root/foo/dir3/es-.*.info']
funnydman
  • 9,083
  • 4
  • 40
  • 55
1

I am not sure of pythonic, but this will be also on possible way

list(map(lambda x: '/root' + x, lst))

Here there is comparison between list comp and map List comprehension vs map

Also thanks to @chris-rands learnt one more way without lambda

list(map('/root'.__add__, lst))
eroot163pi
  • 1,791
  • 1
  • 11
  • 23
0

Just simply write:

lst = ["/foo/dir/c-.*.txt","/foo/dir2/d-.*.svc","/foo/dir3/es-.*.info"]
prefix="/root"

res = [prefix + x for x in lst]
print(res)
devReddit
  • 2,696
  • 1
  • 5
  • 20
0

A simple list comprehension -

lst = ["/foo/dir/c-.*.txt","/foo/dir2/d-.*.svc","/foo/dir3/es-.*.info"]
prefix = '/root'

print([prefix + string for string in lst]) # You can give it a variable if you want
PCM
  • 2,881
  • 2
  • 8
  • 30