Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

python - 如何使用Python从字符串中删除字符(How to delete a character from a string using Python)

There is a string, for example.

(例如,有一个字符串。)

EXAMPLE .

(EXAMPLE 。)

How can I remove the middle character, ie, M from it?

(如何从中删除中间字符(即M ?)

I don't need the code.

(我不需要代码。)

I want to know:

(我想知道:)

  • Do strings in Python end in any special character?

    (Python中的字符串是否以任何特殊字符结尾?)

  • Which is a better way - shifting everything right to left starting from the middle character OR creation of a new string and not copying the middle character?

    (哪种更好的方法-从中间字符开始或从创建新字符串开始,将所有内容从右移到左,而不是复制中间字符?)

  ask by Lazer translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In Python, strings are immutable, so you have to create a new string.

(在Python中,字符串是不可变的,因此您必须创建一个新字符串。)

You have a few options of how to create the new string.

(您有一些有关如何创建新字符串的选项。)

If you want to remove the 'M' wherever it appears:

(如果要删除出现的“ M”,请执行以下操作:)

newstr = oldstr.replace("M", "")

If you want to remove the central character:

(如果要删除中心字符:)

midlen = len(oldstr)/2   # //2 in python 3
newstr = oldstr[:midlen] + oldstr[midlen+1:]

You asked if strings end with a special character.

(您询问字符串是否以特殊字符结尾。)

No, you are thinking like a C programmer.

(不,您在想像C程序员。)

In Python, strings are stored with their length, so any byte value, including \0 , can appear in a string.

(在Python中,字符串按长度存储,因此任何字节值(包括\0 )都可以出现在字符串中。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...