例如,有一个字符串。的例子。
我怎样才能去掉中间的字符,即M ?我不需要密码。我想知道:
Python中的字符串是否以特殊字符结尾? 哪个是更好的方法-从中间字符开始将所有内容从右向左移动或创建一个新字符串而不复制中间字符?
例如,有一个字符串。的例子。
我怎样才能去掉中间的字符,即M ?我不需要密码。我想知道:
Python中的字符串是否以特殊字符结尾? 哪个是更好的方法-从中间字符开始将所有内容从右向左移动或创建一个新字符串而不复制中间字符?
当前回答
如果你想删除/忽略字符串中的字符,例如,你有这个字符串,
“[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 l 0
其他回答
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
我在这里某处见过。
字符串在Python中是不可变的,所以这两个选项的意思基本上是一样的。
如果你想删除/忽略字符串中的字符,例如,你有这个字符串,
“[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 l 0
另一种方法是用一个函数,
下面是通过调用函数从字符串中删除所有元音的方法
def disemvowel(s):
return s.translate(None, "aeiouAEIOU")
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))