替换字符串中的字符实例
- 2024-12-20 08:37:00
- admin 原创
- 147
问题描述:
这个简单的代码只是尝试用冒号替换分号(在 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
我该如何解决这个问题,用冒号替换分号?使用 replace 不起作用,因为该函数不采用索引 - 可能有一些分号我不想替换。
例子
在字符串中我可能有任意数量的分号,例如“Hei der!;Hello there ;!;”
我知道要替换哪些(字符串中有它们的索引)。使用 replace 不起作用,因为我无法使用索引。
解决方案 1:
python 中的字符串是不可变的,所以你不能将它们视为列表并分配给索引。
改用.replace()
:
line = line.replace(';', ':')
如果只需要替换某些分号,则需要更具体。您可以使用切片来隔离要替换的字符串部分:
line = line[:10].replace(';', ':') + line[10:]
这将替换字符串前 10 个字符的所有分号。
解决方案 2:
如果你不想使用,可以执行以下操作,将任何字符替换为给定索引处的相应字符.replace()
word = 'python'
index = 4
char = 'i'
word = word[:index] + char + word[index + 1:]
print word
o/p: pythin
解决方案 3:
将字符串转换为列表;然后您可以单独更改字符。然后您可以使用以下命令将其重新组合在一起.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
解决方案 4:
如果要替换单个分号:
for i in range(0,len(line)):
if (line[i]==";"):
line = line[:i] + ":" + line[i+1:]
但还没有测试过。
解决方案 5:
您不能简单地将值分配给字符串中的字符。使用此方法替换特定字符的值:
name = "India"
result=name .replace("d",'*')
输出:In*ia
另外,如果您想用 替换除第一个字符之外的所有第一个字符,例如 string = babble output = ba*le
代码:
name = "babble"
front= name [0:1]
fromSecondCharacter = name [1:]
back=fromSecondCharacter.replace(front,'*')
return front+back
解决方案 6:
这应该涵盖更普遍的情况,但你应该能够根据自己的目的进行自定义
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)
解决方案 7:
要在字符串上有效地使用 .replace() 方法而无需创建单独的列表,例如查看包含带有一些空格的字符串的列表用户名,我们希望在每个用户名字符串中用下划线替换空格。
names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
usernames = []
要替换每个用户名中的空格,请考虑使用 python 中的范围函数。
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)
解决方案 8:
如果您要用变量“n”中指定的索引值替换,请尝试以下操作:
def missing_char(str, n):
str=str.replace(str[n],":")
return str
解决方案 9:
这个怎么样:
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')
解决方案 10:
要替换特定索引处的字符,函数如下:
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 是索引,c 是字符。
解决方案 11:
我编写了这个方法来替换字符或在特定实例中替换字符串。实例从 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
解决方案 12:
您可以这样做:
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)
解决方案 13:
names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
usernames = []
for i in names:
if " " in i:
i = i.replace(" ", "_")
print(i)
输出:Joey_Tribbiani Monica_Geller Chandler_Bing Phoebe_Buffay
解决方案 14:
我的问题是我有一个数字列表,而我只想替换其中的一部分,所以我这样做:
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']
解决方案 15:
更简单:
input = "a:b:c:d"
output =''
for c in input:
if c==':':
output +='/'
else:
output+=c
print(output)
输出:a/b/c/d
解决方案 16:
我尝试用这个作为二合一
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)
解决方案 17:
更简洁的方式来替换特定索引处的字符
def replace_char(str , index , c):
return str[:index]+c+str[index+1:]