问题:如何使用Python从字符串中删除字符

例如,有一个字符串。EXAMPLE

如何从中删除中间字符M?我不需要代码。我想知道:

  • Python中的字符串是否以任何特殊字符结尾?
  • 哪种更好的方法-从中间字符开始或从创建新字符串开始,将所有内容从右移到左,而不是复制中间字符?

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?

回答 0

在Python中,字符串是不可变的,因此您必须创建一个新字符串。您有一些有关如何创建新字符串的选项。如果要删除出现的“ M”,请执行以下操作:

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

如果要删除中心字符:

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

您询问字符串是否以特殊字符结尾。不,您在想像C程序员。在Python中,字符串按其长度存储,因此任何字节值(包括\0)都可以出现在字符串中。

In Python, strings are immutable, so you have to create a new string. You have a few options of how to create the new string. If you want to remove the ‘M’ wherever it appears:

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. In Python, strings are stored with their length, so any byte value, including \0, can appear in a string.


回答 1

这可能是最好的方法:

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

不用担心字符转移等问题。大多数Python代码以更高的抽象级别进行。

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.


回答 2

要替换特定职位:

s = s[:pos] + s[(pos+1):]

替换特定字符:

s = s.replace('M','')

To replace a specific position:

s = s[:pos] + s[(pos+1):]

To replace a specific character:

s = s.replace('M','')

回答 3

字符串是不可变的。但是您可以将它们转换为可变的列表,然后在更改列表后将其转换回字符串。

s = "this is a string"

l = list(s)  # convert to list

l[1] = ""    # "delete" letter h (the item actually still exists but is empty)
l[1:2] = []  # really delete letter h (the item is actually removed from the list)
del(l[1])    # another way to delete it

p = l.index("a")  # find position of the letter "a"
del(l[p])         # delete it

s = "".join(l)  # convert back to string

您还可以通过从现有字符串中获取所需字符以外的所有内容来创建一个新字符串,如其他字符串所示。

Strings are immutable. But you can convert them to a list, which is mutable, and then convert the list back to a string after you’ve changed it.

s = "this is a string"

l = list(s)  # convert to list

l[1] = ""    # "delete" letter h (the item actually still exists but is empty)
l[1:2] = []  # really delete letter h (the item is actually removed from the list)
del(l[1])    # another way to delete it

p = l.index("a")  # find position of the letter "a"
del(l[p])         # delete it

s = "".join(l)  # convert back to string

You can also create a new string, as others have shown, by taking everything except the character you want from the existing string.


回答 4

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

您不能,因为Python中的字符串是不可变的

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

不。它们类似于字符列表。列表的长度定义字符串的长度,并且没有字符充当终止符。

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

您无法修改现有字符串,因此必须创建一个新字符串,其中包含除中间字符以外的所有内容。

How can I remove the middle character, i.e., M from it?

You can’t, because strings in Python are immutable.

Do strings in Python end in any special character?

No. They are similar to lists of characters; the length of the list defines the length of the string, and no character acts as a terminator.

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?

You cannot modify the existing string, so you must create a new one containing everything except the middle character.


回答 5

使用translate()方法:

>>> s = 'EXAMPLE'
>>> s.translate(None, 'M')
'EXAPLE'

Use the translate() method:

>>> s = 'EXAMPLE'
>>> s.translate(None, 'M')
'EXAPLE'

回答 6

UserString.MutableString

可变方式:

import UserString

s = UserString.MutableString("EXAMPLE")

>>> type(s)
<type 'str'>

# Delete 'M'
del s[3]

# Turn it for immutable:
s = str(s)

UserString.MutableString

Mutable way:

import UserString

s = UserString.MutableString("EXAMPLE")

>>> type(s)
<type 'str'>

# Delete 'M'
del s[3]

# Turn it for immutable:
s = str(s)

回答 7

card = random.choice(cards)
cardsLeft = cards.replace(card, '', 1)

如何从字符串中删除一个字符: 这是一个示例,其中有一堆卡表示为字符串中的字符。其中一个被绘制(为random.choice()函数导入random模块,该函数从字符串中选择一个随机字符)。创建了一个新字符串cardsLeft,以容纳由字符串函数replace()给出的剩余卡片,其中最后一个参数指示仅一个“卡片”将被空字符串替换…

card = random.choice(cards)
cardsLeft = cards.replace(card, '', 1)

How to remove one character from a string: Here is an example where there is a stack of cards represented as characters in a string. One of them is drawn (import random module for the random.choice() function, that picks a random character in the string). A new string, cardsLeft, is created to hold the remaining cards given by the string function replace() where the last parameter indicates that only one “card” is to be replaced by the empty string…


回答 8

def kill_char(string, n): # n = position of which character you want to remove
    begin = string[:n]    # from beginning to n (n not included)
    end = string[n+1:]    # n+1 through end of string
    return begin + end
print kill_char("EXAMPLE", 3)  # "M" removed

我看到这个地方在这里

def kill_char(string, n): # n = position of which character you want to remove
    begin = string[:n]    # from beginning to n (n not included)
    end = string[n+1:]    # n+1 through end of string
    return begin + end
print kill_char("EXAMPLE", 3)  # "M" removed

I have seen this somewhere here.


回答 9

这是我切出“ M”的方法:

s = 'EXAMPLE'
s1 = s[:s.index('M')] + s[s.index('M')+1:]

Here’s what I did to slice out the “M”:

s = 'EXAMPLE'
s1 = s[:s.index('M')] + s[s.index('M')+1:]

回答 10

如果您要删除/忽略字符串中的字符,例如,您拥有此字符串,

“ [11:L:0]”

来自Web API响应或类似CSV文件之类的信息,假设您正在使用请求

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

循环并摆脱不需要的字符:

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

可选拆分,您将能够单独读取值:

listofvalues = line.split(':')

现在访问每个值更容易:

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

这将打印

11

大号

0

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


回答 11

删除一次charsub-string 一次(仅第一次出现):

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

注意:在这里1可以用任何int您要替换的出现次数替换。

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.


回答 12

您可以简单地使用列表理解。

假设您有字符串:,my name is并且想要删除character m。使用以下代码:

"".join([x for x in "my name is" if x is not 'm'])

You can simply use list comprehension.

Assume that you have the string: my name is and you want to remove character m. use the following code:

"".join([x for x in "my name is" if x is not 'm'])

回答 13

from random import randint


def shuffle_word(word):
    newWord=""
    for i in range(0,len(word)):
        pos=randint(0,len(word)-1)
        newWord += word[pos]
        word = word[:pos]+word[pos+1:]
    return newWord

word = "Sarajevo"
print(shuffle_word(word))
from random import randint


def shuffle_word(word):
    newWord=""
    for i in range(0,len(word)):
        pos=randint(0,len(word)-1)
        newWord += word[pos]
        word = word[:pos]+word[pos+1:]
    return newWord

word = "Sarajevo"
print(shuffle_word(word))

回答 14

另一种方法是使用函数

下面是一种仅通过调用函数即可从字符串中删除所有元音的方法

def disemvowel(s):
    return s.translate(None, "aeiouAEIOU")

Another way is with a function,

Below is a way to remove all vowels from a string, just by calling the function

def disemvowel(s):
    return s.translate(None, "aeiouAEIOU")

回答 15

字符串在Python中是不可变的,因此您的两个选项基本上意味着同一件事。

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


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