276

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 occurrences of : in the string that shouldn't be removed.

I am writing my code in Python.

ndmeiri
  • 4,979
  • 12
  • 37
  • 45
Hossein
  • 40,161
  • 57
  • 141
  • 175

5 Answers5

486

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
Bjamse
  • 333
  • 5
  • 17
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • 17
    If this is the accepted answer then the question should have been "how do I remove the first character of a string". – Spaceghost Feb 09 '11 at 14:25
  • 5
    @Spaceghost: The OP states "Specifically I want to remove the first character." – Sven Marnach Feb 09 '11 at 14:27
  • 11
    You are right, I was just responding to the difference between the title and the body of the question.. In hindsight, should have spent the time getting coffee. :-) – Spaceghost Feb 09 '11 at 14:36
52

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))
Spaceghost
  • 6,835
  • 3
  • 28
  • 42
38

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.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
12

Just do this:

r = "hello"
r = r[1:]
print(r) # ello
user14524635
  • 121
  • 1
  • 2
2

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])

Ant
  • 5,151
  • 2
  • 26
  • 43