Remove the first character of a string

后端 未结 5 591
萌比男神i
萌比男神i 2020-12-07 21:38

I would like to remove the first character of a string.

For example, my string starts with a : and I want to remove that only. There are several occurre

相关标签:
5条回答
  • 2020-12-07 21:57

    Depending on the structure of the string, you can use lstrip:

    str = str.lstrip(':')
    

    But this would remove all colons at the beginning, i.e. if you have ::foo, the result would be foo. But this function is helpful if you also have strings that do not start with a colon and you don't want to remove the first character then.

    0 讨论(0)
  • 2020-12-07 22:13

    python 2.x

    s = ":dfa:sif:e"
    print s[1:]
    

    python 3.x

    s = ":dfa:sif:e"
    print(s[1:])
    

    both prints

    dfa:sif:e
    
    0 讨论(0)
  • 2020-12-07 22:13

    Your problem seems unclear. You say you want to remove "a character from a certain position" then go on to say you want to remove a particular character.

    If you only need to remove the first character you would do:

    s = ":dfa:sif:e"
    fixed = s[1:]
    

    If you want to remove a character at a particular position, you would do:

    s = ":dfa:sif:e"
    fixed = s[0:pos]+s[pos+1:]
    

    If you need to remove a particular character, say ':', the first time it is encountered in a string then you would do:

    s = ":dfa:sif:e"
    fixed = ''.join(s.split(':', 1))
    
    0 讨论(0)
  • 2020-12-07 22:15

    Just do this:

    r = "hello"
    r = r[1:]
    print(r) # ello
    
    0 讨论(0)
  • 2020-12-07 22:17

    deleting a char:

    def del_char(string, indexes):
    
        'deletes all the indexes from the string and returns the new one'
    
        return ''.join((char for idx, char in enumerate(string) if idx not in indexes))
    

    it deletes all the chars that are in indexes; you can use it in your case with del_char(your_string, [0])

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