Python 替换字符串中字符的实例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12723751/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replacing instances of a character in a string
提问by The Unfun Cat
This simple code that simply tries to replace semicolons (at i-specified postions) by colons does not work:
这个简单的代码只是试图用冒号替换分号(在 i 指定的位置)不起作用:
for i in range(0,len(line)):
if (line[i]==";" and i in rightindexarray):
line[i]=":"
It gives the error
它给出了错误
line[i]=":"
TypeError: 'str' object does not support item assignment
How can I work around this to replace the semicolons by colons? Using replace does not work as that function takes no index- there might be some semicolons I do not want to replace.
我该如何解决这个问题以用冒号替换分号?使用 replace 不起作用,因为该函数没有索引 - 可能有一些我不想替换的分号。
Example
例子
In the string I might have any number of semicolons, eg "Hei der! ; Hello there ;!;"
在字符串中,我可能有任意数量的分号,例如“Hei der! ; Hello there ;!;”
I know which ones I want to replace (I have their index in the string). Using replace does not work as I'm not able to use an index with it.
我知道我想替换哪些(我在字符串中有它们的索引)。使用 replace 不起作用,因为我无法使用它的索引。
采纳答案by Martijn Pieters
Strings in python are immutable, so you cannot treat them as a list and assign to indices.
python 中的字符串是不可变的,因此您不能将它们视为列表并分配给索引。
Use .replace()instead:
使用.replace()来代替:
line = line.replace(';', ':')
If you need to replace only certainsemicolons, you'll need to be more specific. You could use slicing to isolate the section of the string to replace in:
如果您只需要替换某些分号,则需要更具体。您可以使用切片来隔离要替换的字符串部分:
line = line[:10].replace(';', ':') + line[10:]
That'll replace all semi-colons in the first 10 characters of the string.
这将替换字符串前 10 个字符中的所有分号。
回答by Vic
If you want to replace a single semicolon:
如果要替换单个分号:
for i in range(0,len(line)):
if (line[i]==";"):
line = line[:i] + ":" + line[i+1:]
Havent tested it though.
虽然没有测试过。
回答by inspectorG4dget
This should cover a slightly more general case, but you should be able to customize it for your purpose
这应该涵盖更一般的情况,但您应该能够根据自己的目的对其进行自定义
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)
Hope this helps
希望这可以帮助
回答by nneonneo
Turn the string into a list; then you can change the characters individually. Then you can put it back together with .join:
将字符串变成列表;然后您可以单独更改字符。然后你可以把它放回去.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
回答by Dineshs91
You can do the below, to replace any char with a respective char at a given index, if you wish not to use .replace()
如果您不想使用,您可以执行以下操作,用给定索引处的相应字符替换任何字符 .replace()
word = 'python'
index = 4
char = 'i'
word = word[:index] + char + word[index + 1:]
print word
o/p: pythin
回答by Bipin Shetty
If you are replacing by an index value specified in variable 'n', then try the below:
如果您要替换为变量“n”中指定的索引值,请尝试以下操作:
def missing_char(str, n):
str=str.replace(str[n],":")
return str
回答by Darshan Jain
You cannot simply assign value to a character in the string. Use this method to replace value of a particular character:
您不能简单地为字符串中的字符赋值。使用此方法替换特定字符的值:
name = "India"
result=name .replace("d",'*')
Output: In*ia
输出:In*ia
Also, if you want to replace say * for all the occurrences of the first character except the first character, eg. string = babble output = ba**le
此外,如果您想替换除第一个字符之外的所有第一个字符的出现的 say *,例如。字符串 = babble 输出 = ba**le
Code:
代码:
name = "babble"
front= name [0:1]
fromSecondCharacter = name [1:]
back=fromSecondCharacter.replace(front,'*')
return front+back
回答by Dylan Maulucci
How about this:
这个怎么样:
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')
回答by Sanket Hire
To replace a character at a specific index, the function is as follows:
要替换特定索引处的字符,函数如下:
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
where s is a string, n is index and c is a character.
其中 s 是一个字符串,n 是索引,c 是一个字符。
回答by Matt Farguson
I wrote this method to replace characters or replace strings at a specific instance. instances start at 0 (this can easily be changed to 1 if you change the optional inst argument to 1, and test_instance variable to 1.
我编写了这个方法来替换特定实例中的字符或替换字符串。实例从 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

