替换字符串中字符的实例

这个简单的代码仅仅尝试用冒号替换分号(在 i 指定的位置)是不起作用的:

for i in range(0,len(line)):
if (line[i]==";" and i in rightindexarray):
line[i]=":"

它给出了错误

line[i]=":"
TypeError: 'str' object does not support item assignment

如何使用冒号替换分号?使用替换不起作用,因为该函数没有索引-可能有一些分号我不想替换。

例子

在字符串中,我可能有任意数量的分号,例如“黑德! ; 你好; ! ;”

我知道我想要替换哪一个(我在字符串中有它们的索引)。使用替换不起作用,因为我不能对它使用索引。

495819 次浏览

Python 中的字符串是不可变的,因此不能将它们视为列表并分配给索引。

改为使用 .replace():

line = line.replace(';', ':')

如果只需要替换 当然分号,则需要更具体一些。您可以使用切片来隔离要替换的字符串部分:

line = line[:10].replace(';', ':') + line[10:]

它将替换字符串前10个字符中的所有分号。

如果要替换单个分号:

for i in range(0,len(line)):
if (line[i]==";"):
line = line[:i] + ":" + line[i+1:]

不过还没测试过。

这应该涵盖一个稍微更一般的情况,但是您应该能够根据自己的目的对其进行定制

def selectiveReplace(myStr):
answer = []
for index,char in enumerate(myStr):
if char == ';':
if index%2 == 1: # replace ';' in even indices with ":"
answer.append(":")
else:
answer.append("!") # replace ';' in odd indices with "!"
else:
answer.append(char)
return ''.join(answer)

将字符串转换为列表; 然后可以单独更改字符。然后你可以把它和 .join放在一起:

s = 'a;b;c;d'
slist = list(s)
for i, c in enumerate(slist):
if slist[i] == ';' and 0 <= i <= 3: # only replaces semicolons in the first part of the text
slist[i] = ':'
s = ''.join(slist)
print s # prints a:b:c;d

如果不希望使用 .replace(),可以执行以下操作,用给定索引处的相应字符替换任何字符

word = 'python'
index = 4
char = 'i'


word = word[:index] + char + word[index + 1:]
print word


o/p: pythin

如果要用变量‘ n’中指定的索引值替换,请尝试以下操作:

def missing_char(str, n):
str=str.replace(str[n],":")
return str

不能简单地为字符串中的字符赋值。 使用此方法替换特定字符的值:

name = "India"
result=name .replace("d",'*')

产出: In * ia

另外,如果您想替换 say * 中除了第一个字符以外的所有第一个字符的匹配项, String = babble output = ba * * le

密码:

name = "babble"
front= name [0:1]
fromSecondCharacter = name [1:]
back=fromSecondCharacter.replace(front,'*')
return front+back

这样吧:

sentence = 'After 1500 years of that thinking surpressed'


sentence = sentence.lower()


def removeLetter(text,char):


result = ''
for c in text:
if c != char:
result += c
return text.replace(char,'*')
text = removeLetter(sentence,'a')

要替换特定索引处的字符,函数如下:

def replace_char(s , n , c):
n-=1
s = s[0:n] + s[n:n+1].replace(s[n] , c) + s[n+1:]
return s

其中 s 是字符串,n 是 index,c 是字符。

我编写此方法是为了在特定实例中替换字符或替换字符串。Instance 从0开始(如果您将可选的 inst 参数改为1,将 test _ instance 变量改为1,那么可以很容易地将其改为1。

def replace_instance(some_word, str_to_replace, new_str='', inst=0):
return_word = ''
char_index, test_instance = 0, 0
while char_index < len(some_word):
test_str = some_word[char_index: char_index + len(str_to_replace)]
if test_str == str_to_replace:
if test_instance == inst:
return_word = some_word[:char_index] + new_str + some_word[char_index + len(str_to_replace):]
break
else:
test_instance += 1
char_index += 1
return return_word

在不创建单独列表的情况下,对字符串有效地使用. place ()方法 例如,看一下包含带有一些空格的字符串的用户名列表,我们希望在每个用户名字符串中用下划线替换空格。

names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
usernames = []

要替换每个用户名中的空白,可以考虑使用 python 中的 range 函数。

for name in names:
usernames.append(name.lower().replace(' ', '_'))


print(usernames)

或者如果你想使用一个列表:

for user in range(len(names)):
names[user] = names[user].lower().replace(' ', '_')


print(names)

你可以这样做:

string = "this; is a; sample; ; python code;!;" #your desire string
result = ""
for i in range(len(string)):
s = string[i]
if (s == ";" and i in [4, 18, 20]): #insert your desire list
s = ":"
result = result + s
print(result)
names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]


usernames = []


for i in names:
if " " in i:
i = i.replace(" ", "_")
print(i)

产出: 乔伊,崔比亚尼 盖勒 钱德宾 Phoebe _ Buffay

我的问题是我有一个数字列表,我只想替换其中的一部分,所以我这样做:

original_list = ['08113', '09106', '19066', '17056', '17063', '17053']


# With this part I achieve my goal
cves_mod = []
for i in range(0,len(res_list)):
cves_mod.append(res_list[i].replace(res_list[i][2:], '999'))
cves_mod


# Result
cves_mod
['08999', '09999', '19999', '17999', '17999', '17999']

更简单的是:

input = "a:b:c:d"
output =''
for c in input:
if c==':':
output +='/'
else:
output+=c
print(output)

输出: a/b/c/d

我试着用这个来代替二进制

usernames = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]


# write your for loop here
for user in range(0,len(usernames)):
usernames[user] = usernames[user].lower().replace(' ', '_')


print(usernames)

替换特定索引处字符的更干净的方法

def replace_char(str , index , c):
return str[:index]+c+str[index+1:]