[英]Replacing instances of a character in a string
这个简单的代码试图用冒号替换分号(在 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
我该如何解决这个问题,用冒号替换分号? 使用替换不起作用,因为该函数不需要索引 - 可能有一些分号我不想替换。
例子
在字符串中,我可能有任意数量的分号,例如“Hei der! ; Hello there ;!;”
我知道要替换哪些(我在字符串中有它们的索引)。 使用替换不起作用,因为我无法使用索引。
python 中的字符串是不可变的,因此您不能将它们视为列表并分配给索引。
使用.replace()
代替:
line = line.replace(';', ':')
如果您只需要替换某些分号,则需要更具体。 您可以使用切片来隔离要替换的字符串部分:
line = line[:10].replace(';', ':') + line[10:]
这将替换字符串前 10 个字符中的所有分号。
如果您不想使用.replace()
word = 'python'
index = 4
char = 'i'
word = word[:index] + char + word[index + 1:]
print word
o/p: pythin
将字符串变成列表; 然后您可以单独更改字符。 然后你可以把它和.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
如果要替换单个分号:
for i in range(0,len(line)):
if (line[i]==";"):
line = line[:i] + ":" + line[i+1:]
不过还没有测试过。
您不能简单地为字符串中的字符赋值。 使用此方法替换特定字符的值:
name = "India"
result=name .replace("d",'*')
输出:In*ia
此外,如果您想替换除第一个字符之外的所有第一个字符出现的say *,例如。 字符串 = babble 输出 = ba**le
代码:
name = "babble"
front= name [0:1]
fromSecondCharacter = name [1:]
back=fromSecondCharacter.replace(front,'*')
return front+back
这应该涵盖更一般的情况,但您应该能够根据您的目的对其进行自定义
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)
要在字符串上有效地使用 .replace() 方法而不创建单独的列表,例如查看包含带有一些空格的字符串的列表用户名,我们希望在每个用户名字符串中用下划线替换空格。
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)
这个怎么样:
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')
如果您要替换为变量“n”中指定的索引值,请尝试以下操作:
def missing_char(str, n):
str=str.replace(str[n],":")
return str
替换特定索引处的字符,函数如下:
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 是字符。
我编写了这个方法来替换字符或替换特定实例的字符串。 实例从 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
你可以这样做:
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)
输出:Joey_Tribbiani Monica_Geller Chandler_Bing 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
我尝试将其用作 2 合 1
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:]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.