0

I would like to take a list of strings which represent individual lines entered in a CLI and put '~$ ' at the beginning so when I display them it is more clear that they are command lines. I tried this

command = # a multiline block of command lines
lines = command.split('\n')
for l in lines:
    l = '~$ ' + l
for l in lines: print l

But this modifies the temporary variable l I think without going back and changing the actual value in the list. If I put the print inside of the first loop it prints with the correct values, but if I do it like shown the change isn't made. Thanks in advance for any help.

1
  • Did you make any attempt at all to solve this on your own? Commented Jun 19, 2013 at 21:04

2 Answers 2

9

Use a list comprehension:

lines = ['~$ ' + line for line in command.split('\n')]

If you have to use a for loop, you'd use enumerate() to include an index so you can replace the individual items in the list:

for i, line in enumerate(lines):
    lines[i] = '~$ ' + line
Sign up to request clarification or add additional context in comments.

7 Comments

@mgilson: tsk, tsk, have you not yet learned that I keep on editing for a while? :-P
note the new binding here, in case this is a global variable or something.
I think I prefer slice-assignment here (over enumerate with the loop): lines[:] = ['~$ '+line for line in lines]
@mgilson: if the list is references elsewhere, sure.
the enumerate solution can be a bit misleading - it looks like independent values.
|
1

The functional way:

list(map(lambda s: '~$ ' + s, command.splitlines()))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.