有一个字符串,例如EXAMPLE
。
我该如何从中删除中间的字符,即M
? 我不需要代码。 我想知道以下内容:
- Python中的字符串是否以任何特殊字符结尾?
- 哪种方法更好- 从中间字符开始向右移动所有内容左侧的内容,还是创建一个新字符串并不复制中间字符?
my name is
,并且你想要移除字符m
。请使用以下代码:"".join([x for x in "my name is" if x is not 'm'])
要删除一个 char
或一个 sub-string
(只删除第一次出现的),请执行以下操作:
main_string = main_string.replace(sub_str, replace_with, 1)
注意:这里的1
可以替换为任何整数int
,来指定你想要替换的次数。
这是我用来切割出"M"的方法:
s = 'EXAMPLE'
s1 = s[:s.index('M')] + s[s.index('M')+1:]
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
L
0
Python 3.9+引入了两种新的字符串删除方法。
#str.removeprefix("prefix_to_be_removed")
#str.removesuffix("suffix_to_be_removed")
s='EXAMPLE'
s = s[:3] + s[3:].removeprefix('M')
或者
s = s[:4].removesuffix('M') + s[4:]
#output'EXAPLE'
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))
在Python中,字符串是不可变的,因此你的两个选项基本上意思相同。