1

I am searching for an easier way to remove the '-' in front of each string in a list. (only the first '-' if there is one in front of the string)

note_tmp = [
    "-some-text",
    "-other text",
    "another-one",
    "-text number four"
]
note_done = []
for note in note_tmp:
    if note.startswith("-"):
        note_done.append(note[1:])
    else:
        note_done.append(note)

print(note_done)

I thing this can be written much easier...

Thanks for your help ;)

swift-lynx
  • 3,219
  • 3
  • 26
  • 45
  • I don't know if there is some method; but i think; those methods would at last will do the same; ie. iteration and checking; then modifying and appending; which ofcourse you have done. Also one thing can be shortened; remove else block and directly modify the main list(if there is a safe copy somewhere) – Vicrobot Jan 10 '19 at 13:27

3 Answers3

3

str.lstrip('-') should do:

In [83]: note_tmp = [
    ...:     "-some-text",
    ...:     "-other text",
    ...:     "another-one",
    ...:     "-text number four"
    ...: ]

In [84]: [s.lstrip('-') for s in note_tmp]
Out[84]: ['some-text', 'other text', 'another-one', 'text number four']

S.lstrip([chars]) -> str

Return a copy of the string S with leading whitespace removed. If chars is given and not None, remove characters in chars instead.

heemayl
  • 39,294
  • 7
  • 70
  • 76
2

You may use str.lstrip() with list comprehension to achieve this as:

my_list = [
    "-some-text",
    "-other text",
    "another-one",
    "-text number four"
]

new_list = [s.lstrip('-') for s in my_list]

where new_list will hold value:

['some-text', 'other text', 'another-one', 'text number four']
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
1

Just adding an alternative approach, using list slicing and list comprehension;

note_tmp = [
        "-some-text",
        "-other text",
        "another-one",
        "-text number four"
    ]

new_note_tmp = [x[1:] if x[0] == '-' else x for x in note_tmp]

print(new_note_tmp)

>>>['some-text', 'other text', 'another-one', 'text number four']
Nordle
  • 2,915
  • 3
  • 16
  • 34
  • list comprehension isn't making it any shorter – Vicrobot Jan 10 '19 at 13:21
  • I beg to differ, as it is quite clearly 5 lines shorter. Furthermore, no-one has asked for a 'shorter' solution. – Nordle Jan 10 '19 at 13:23
  • i can make it one line code; but that is also not shorter because I think shorter means less in time- space complexity; and not the lines that the code acquires. – Vicrobot Jan 10 '19 at 13:25
  • But it does have the benefit that it only removes one '-' at the start of the string, unlike the .lstrip() versions. – simon3270 Jan 10 '19 at 13:25