Python 删除字符串的第一个字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4945548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 18:17:13  来源:igfitidea点击:

Remove the first character of a string

pythonstring

提问by Hossein

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.

例如,我的字符串以 a 开头,:我只想删除它。:字符串中有多次出现不应删除。

I am writing my code in Python.

我正在用 Python 编写我的代码。

采纳答案by Sven Marnach

python 2.x

蟒蛇2.x

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

python 3.x

蟒蛇 3.x

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

both prints

两个版画

dfa:sif:e

回答by Felix Kling

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

根据字符串的结构,您可以使用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.

但这将删除开头的所有冒号,即如果您有::foo,结果将是foo。但是,如果您还有不以冒号开头的字符串并且您不想删除第一个字符,则此函数很有用。

回答by Ant

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

它删除索引中的所有字符;你可以在你的情况下使用它del_char(your_string, [0])

回答by Spaceghost

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