如何使用python从字符串中删除字符?

时间:2022-11-29 10:50:56

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, what I want to know is

我怎么才能去掉中间的字符呢?我不需要代码,我想知道的是。

  • 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?
  • 这是一种更好的方式——将所有的东西都从中间的字符开始,或者创建一个新的字符串,而不是复制中间的字符?

13 个解决方案

#1


412  

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:

在Python中,字符串是不可变的,所以必须创建一个新字符串。您有几个如何创建新字符串的选项。如果你想删除“M”,无论它出现在哪里:

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

If you want to remove the central character:

如果您想删除中心字符:

midlen = len(oldstr)/2
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.

你问字符串是否以一个特殊的字符结束。不,你像个C程序员一样思考。在Python中,字符串以其长度存储,因此任何字节值(包括\0)都可以出现在字符串中。

#2


50  

This is probably the best way:

这可能是最好的方法:

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

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

不要担心角色的变化。大多数python发生在更高层次的抽象上。

#3


40  

To replace a specific position:

取代某一特定职位:

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

To replace a specific character:

替换一个特定的字符:

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

#4


20  

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.

您还可以创建一个新的字符串,就像其他人所显示的那样,除了从现有字符串中获取的字符以外,其他所有内容都可以使用。

#5


9  

I didn't see see the translate() method mentioned, so here goes:

我没有看到所提到的翻译()方法,所以这里是:

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

#6


8  

How can I remove the middle character

如何去掉中间的字符?

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

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

Do strings in python end in any special character?

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

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.

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

#7


5  

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

如何从字符串中删除一个字符:这里有一个例子,其中有一组字符,表示为字符串中的字符。其中一个是绘制的(随机的导入随机模块,选择()函数,在字符串中选择一个随机字符)。一个新的字符串,cardsLeft,被创建用来保存字符串函数replace()所给出的剩余的卡片,其中最后一个参数表示只有一个“卡片”将被空字符串替换…

#8


4  

UserString.MutableString

UserString.MutableString

mutable way:

可变的方法:

import UserString

s = UserString.MutableString("EXAMPLE")

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

#del 'M'
del s[3]

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

#9


3  

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

我在这里的某个地方见过。

#10


3  

I am just learning to code. Here's what I did to slice out the "M"

我只是在学习编码。这就是我所做的

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

#11


2  

If you want to delete/ignore characters in within a string so for instance you have this string

如果你想在字符串中删除/忽略字符,比如你有这个字符串。

"[11:L:0]"

“[11:L:0]”

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

从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

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

11

L

l

0

0

#12


0  

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

#13


-3  

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

字符串在Python中是不可变的,所以你的选项基本上都是一样的。

#1


412  

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:

在Python中,字符串是不可变的,所以必须创建一个新字符串。您有几个如何创建新字符串的选项。如果你想删除“M”,无论它出现在哪里:

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

If you want to remove the central character:

如果您想删除中心字符:

midlen = len(oldstr)/2
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.

你问字符串是否以一个特殊的字符结束。不,你像个C程序员一样思考。在Python中,字符串以其长度存储,因此任何字节值(包括\0)都可以出现在字符串中。

#2


50  

This is probably the best way:

这可能是最好的方法:

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

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

不要担心角色的变化。大多数python发生在更高层次的抽象上。

#3


40  

To replace a specific position:

取代某一特定职位:

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

To replace a specific character:

替换一个特定的字符:

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

#4


20  

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.

您还可以创建一个新的字符串,就像其他人所显示的那样,除了从现有字符串中获取的字符以外,其他所有内容都可以使用。

#5


9  

I didn't see see the translate() method mentioned, so here goes:

我没有看到所提到的翻译()方法,所以这里是:

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

#6


8  

How can I remove the middle character

如何去掉中间的字符?

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

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

Do strings in python end in any special character?

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

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.

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

#7


5  

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

如何从字符串中删除一个字符:这里有一个例子,其中有一组字符,表示为字符串中的字符。其中一个是绘制的(随机的导入随机模块,选择()函数,在字符串中选择一个随机字符)。一个新的字符串,cardsLeft,被创建用来保存字符串函数replace()所给出的剩余的卡片,其中最后一个参数表示只有一个“卡片”将被空字符串替换…

#8


4  

UserString.MutableString

UserString.MutableString

mutable way:

可变的方法:

import UserString

s = UserString.MutableString("EXAMPLE")

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

#del 'M'
del s[3]

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

#9


3  

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

我在这里的某个地方见过。

#10


3  

I am just learning to code. Here's what I did to slice out the "M"

我只是在学习编码。这就是我所做的

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

#11


2  

If you want to delete/ignore characters in within a string so for instance you have this string

如果你想在字符串中删除/忽略字符,比如你有这个字符串。

"[11:L:0]"

“[11:L:0]”

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

从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

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

11

L

l

0

0

#12


0  

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

#13


-3  

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

字符串在Python中是不可变的,所以你的选项基本上都是一样的。