问题:替换字符串中字符的实例

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

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

This simple code that simply tries to replace semicolons (at i-specified postions) by colons does not work:

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.

Example

In the string I might have any number of semicolons, eg “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.


回答 0

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

使用.replace()来代替:

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

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

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

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

Strings in python are immutable, so you cannot treat them as a list and assign to indices.

Use .replace() instead:

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

If you need to replace only certain semicolons, 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.


回答 1

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

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

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

o/p: pythin

You can do the below, to replace any char with a respective char at a given index, if you wish not to use .replace()

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

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

o/p: pythin

回答 2

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

Turn the string into a list; then you can change the characters individually. Then you can put it back together with .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

回答 3

如果要替换单个分号:

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

Havent对此进行了测试。

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.


回答 4

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

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)

希望这可以帮助

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


回答 5

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

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

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

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

Code:

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

回答 6

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

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

If you are replacing by an index value specified in variable ‘n’, then try the below:

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

回答 7

这个怎么样:

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

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

回答 8

为了在字符串上有效地使用.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)

to use the .replace() method effectively on string without creating a separate list for example take a look at the list username containing string with some white space, we want to replace the white space with an underscore in each of the username string.

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

to replace the white spaces in each username consider using the range function in python.

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

print(usernames)

回答 9

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

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是字符。

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.


回答 10

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

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.

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

回答 11

你可以这样做:

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)

You can do this:

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)

回答 12

名称= [“ 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

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

usernames = []

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

Output: Joey_Tribbiani Monica_Geller Chandler_Bing Phoebe_Buffay


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。