简体   繁体   English

删除字符串的第一个字符

[英]Remove the first character of a string

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 编写代码。

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

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

Depending on the structure of the string, you can use lstrip :根据字符串的结构,您可以使用lstrip

str = str.lstrip(':')

But this would remove all colons at the beginning, ie if you have ::foo , the result would be foo .但这会删除开头的所有冒号,即如果您有::foo ,结果将是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.但是如果您还有不以冒号开头的字符串并且您不想删除第一个字符,则此函数很有用。

Just do this:只需这样做:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM