问题:删除字符串的第一个字符

我想删除字符串的第一个字符。

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

我正在用Python编写代码。

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.


回答 0

python 2.x

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

python 3.x

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

都印

dfa:sif:e

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

回答 1

您的问题似乎不清楚。您说要删除“某个位置的字符”,然后继续说要删除特定字符。

如果只需要删除第一个字符,则可以执行以下操作:

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

如果要删除特定位置的字符,可以执行以下操作:

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

如果您需要删除某个特定字符,例如在字符串中首次遇到该字符,请说::

s = ":dfa:sif:e"
fixed = ''.join(s.split(':', 1))

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

回答 2

根据字符串的结构,可以使用lstrip

str = str.lstrip(':')

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

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.


回答 3

删除字符:

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

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

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


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。