How to delete the very last character from every string in a list of strings

后端 未结 4 593
长发绾君心
长发绾君心 2021-01-11 12:55

I have the strings \'80010\', \'80030\', \'80050\' in a list, as in

test = [\'80010\',\'80030\',\'80050\']

How can I delete the very last

相关标签:
4条回答
  • 2021-01-11 13:07

    You are not so far off. Using the slice notation [:-1] is the right approach. Just combine it with a list comprehension:

    >>> test = ['80010','80030','80050']
    >>> [x[:-1] for x in test]
    ['8001', '8003', '8005']
    

    somestring[:-1] gives you everything from the character at position 0 (inclusive) to the last character (exclusive).

    0 讨论(0)
  • 2021-01-11 13:18
    test = ["80010","80030","80050"]
    newtest = [x[:-1] for x in test]
    

    New test will contain the result ["8001","8003","8005"].

    [x[:-1] for x in test] creates a new list (using list comprehension) by looping over each item in test and putting a modified version into newtest. The x[:-1] means to take everything in the string value x up to but not including the last element.

    0 讨论(0)
  • 2021-01-11 13:20

    Just to show a slightly different solution than comprehension, Given that other answers already explained slicing, I just go through at the method.

    With the map function.

    test = ['80010','80030','80050']
    print map(lambda x: x[:-1],test)
    # ['8001', '8003', '8005']
    

    For more information about this solution, please read the brief explanation I did in another similar question.

    Convert a list into a sequence of string triples

    0 讨论(0)
  • 2021-01-11 13:23

    In python @Matthew solution is perfect. But if indeed you are a beginer in coding in general, I must recommend this, less elegant for sure but the only way in many other scenario :

    #variables declaration
    test = ['80010','80030','80050'] 
    lenght = len(test)                 # for reading and writing sakes, len(A): lenght of A
    newtest = [None] * lenght          # newtest = [none, none, none], go look up empty array creation
    strLen = 0                         # temporary storage
    
    #adding in newtest every element of test but spliced
    for i in range(0, lenght):         # for loop
        str = test[i]                  # get n th element of test
        strLen = len (str)             # for reading sake, the lenght of string that will be spliced
        newtest[i] = str[0:strLen - 1] # n th element of newtest is the spliced n th element from test
    
    #show the results
    print (newtest)                    # ['8001','8003','8005']
    

    ps : this scripts, albeit not being the best, works in python ! Good luck to any programmer newcommer.

    0 讨论(0)
提交回复
热议问题