替换字符串中字符的实例


119

这个简单的代码仅尝试用冒号替换分号(在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;!;”

我知道我想替换哪些(我在字符串中有索引)。使用替换无法正常工作,因为我无法对其使用索引。


1
你知道str.replace()BIF吗?
LarsVegas 2012年

2
是的,正如我在问题中解释的那样。我还解释了为什么这对我不起作用。
Unfun Cat,2012年

使用str.find() 代替查找分号的位置,然后使用切片提取子字符串。
LarsVegas 2012年

1
然后,您需要更具体地说明什么是有效的替代品。如果您的无效代码是可变的,它将替换字符串中的所有分号。
马丁·彼得斯

1
@TheUnfunCat:首先如何获取索引?可能有更好的解决方案(例如正则表达式)
nneonneo 2012年

Answers:


206

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

使用.replace()来代替:

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

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

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

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


这对Unicode字符有效吗?它似乎对我不起作用。
Steven2163712

@ Steven2163712:所有文本都是Unicode,所以是的,这适用于所有字符。没有具体的示例,我无法帮助您解决特定的问题。
马丁·彼得斯

62

如果您不想使用以下字符,可以执行以下操作,以给定索引将任何字符替换为相应的字符: .replace()

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

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

o/p: pythin

7
这应该是公认的答案,直接回答问题。这是我到目前为止发现的最简单的方法。
Flare Cat

24

把字符串变成一个列表;那么您可以单独更改字符。然后,您可以将其放回原处.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

6

如果要替换单个分号:

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

Havent对此进行了测试。


3
这可以工作(+1),但是效率很低,因为每次遇到';'时都要创建一个新字符串。
inspectorG4dget

@ inspectorG4dget,您是对的,它是一种快速又肮脏的解决方案(仅一次)。
Vic 2012年

实际上,@ inspectorG4dget,接受的答案是否会遇到相同的问题?
维克

2
line.replace(src,dst)才不是。line[:10].replace(src,dst) + line[10:]确实,但严重程度要低得多。假设line = ';'*12。您的解决方案将构建一个新字符串12次。接受的解决方案将执行一次。
inspectorG4dget

3

这应该涵盖了更一般的情况,但是您应该能够针对自己的目的对其进行自定义

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)

希望这可以帮助


3

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

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

输出:In * ia

另外,如果要替换第一个字符以外的所有第一个字符,请说*,例如。字符串=混音输出= ba ** le

码:

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

1

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

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

1
该解决方案的问题在于它将替换位置n上所有出现的字符,而
问问

确实,解决方案不佳!
Erhard Dinhobl

1

这个怎么样:

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')

1

为了在字符串上有效地使用.replace()方法而不创建单独的列表,例如查看包含有空格的字符串的列表用户名,我们希望在每个用户名字符串中用下划线替换空格。

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

要替换每个用户名中的空格,请考虑在python中使用range函数。

for i in range(len(usernames)):
    usernames[i] = usernames[i].lower().replace(" ", "_")

print(usernames)

0

要替换特定索引处的字符,功能如下:

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

我写了这种方法来替换字符或替换特定实例的字符串。实例从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

0

你可以这样做:

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)

0

名称= [“ Joey Tribbiani”,“ Monica Geller”,“ Chandler Bing”,“ Phoebe Buffay”]

用户名= []

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

o,p Joey_Tribbiani Monica_Geller Chandler_Bing Phoebe_Buffay


1
谢谢,穆罕默德,我是初学者,我会努力的。
Kasem007
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.