How to delete a character from a string using Pyth

2019-01-02 16:14发布

There is a string, for example. EXAMPLE.

How can I remove the middle character, i.e., M from it? I don't need the code. I want to know:

  • Do strings in Python end in any special character?
  • 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?

标签: python string
15条回答
柔情千种
2楼-- · 2019-01-02 16:48

Strings are immutable in Python so both your options mean the same thing basically.

查看更多
唯独是你
3楼-- · 2019-01-02 16:49

Here's what I did to slice out the "M":

s = 'EXAMPLE'
s1 = s[:s.index('M')] + s[s.index('M')+1:]
查看更多
春风洒进眼中
4楼-- · 2019-01-02 16:51

Use the translate() method:

>>> s = 'EXAMPLE'
>>> s.translate(None, 'M')
'EXAPLE'
查看更多
人气声优
5楼-- · 2019-01-02 16:54

This is probably the best way:

original = "EXAMPLE"
removed = original.replace("M", "")

Don't worry about shifting characters and such. Most Python code takes place on a much higher level of abstraction.

查看更多
倾城一夜雪
6楼-- · 2019-01-02 16:54

If you want to delete/ignore characters in a string, and, for instance, you have this string,

"[11:L:0]"

from a web API response or something like that, like a CSV file, let's say you are using requests

import requests
udid = 123456
url = 'http://webservices.yourserver.com/action/id-' + udid
s = requests.Session()
s.verify = False
resp = s.get(url, stream=True)
content = resp.content

loop and get rid of unwanted chars:

for line in resp.iter_lines():
  line = line.replace("[", "")
  line = line.replace("]", "")
  line = line.replace('"', "")

Optional split, and you will be able to read values individually:

listofvalues = line.split(':')

Now accessing each value is easier:

print listofvalues[0]
print listofvalues[1]
print listofvalues[2]

This will print

11

L

0

查看更多
忆尘夕之涩
7楼-- · 2019-01-02 16:54

To delete a char or a sub-string once (only the first occurrence):

main_string = main_string.replace(sub_str, replace_with, 1)

NOTE: Here 1 can be replaced with any int for the number of occurrence you want to replace.

查看更多
登录 后发表回答