Remove the first character of a string

PythonString

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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

Solution 3 - Python

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.

Solution 4 - Python

Just do this:

r = "hello"
r = r[1:]
print(r) # ello

Solution 5 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHosseinView Question on Stackoverflow
Solution 1 - PythonSven MarnachView Answer on Stackoverflow
Solution 2 - PythonSpaceghostView Answer on Stackoverflow
Solution 3 - PythonFelix KlingView Answer on Stackoverflow
Solution 4 - Pythonuser14524635View Answer on Stackoverflow
Solution 5 - PythonAntView Answer on Stackoverflow