1

Using Python, I would like to convert a list to string looks like this: I'm looking for a more elegant way then loops

cmd = ['cd ..', 'pwd', 'howami']

"cd..; pwd; howami"

Thanks in advance (it is my first question BTW, please be gentle)

Roy

for cmdStr in cmd:
    
   cmdString += cmdStr + '; '

cmdString.rstrip('; ')

3 Answers3

2

You can use the join function.

"; ".join(cmd)

output

cd ..; pwd; howami
Origin
  • 1,182
  • 1
  • 10
  • 25
2

The method you are looking for is join. In your example it would look like this:

cmd = ['cd ..', 'pwd', 'howami']

"; ".join(cmd)

More on join in python docs: https://docs.python.org/3/library/stdtypes.html#str.join

w8eight
  • 605
  • 1
  • 6
  • 21
0

Different ways you can use

Using functools.reduce method

from functools import reduce
cmd = ['cd ..', 'pwd', 'howami']
string = reduce(lambda a, b : a+ "; " +str(b), cmd)
print(string)  

Using enumerate function

cmd = ['cd ..', 'pwd', 'howami']
string = '; '.join([str(elem) for i,elem in enumerate(cmd)])
print(string)

Using map()

cmd = ['cd ..', 'pwd', 'howami']

string =  '; '.join(map(str, cmd))
print(string) 
justjokingbro
  • 169
  • 2
  • 13
  • Using enumerate is not necessary as you are not accessing index anywhere. Ensuring that input is list of strings is fine tho. The option with functools isn't more "elegant" as op mentioned, it adds another import, use lambda function, which makes it less readable. – w8eight Oct 31 '22 at 10:53
  • yeah you are correct about it .i just showed another ways you can use or you can implement it – justjokingbro Nov 01 '22 at 11:40