Lin Ma
Lin Ma

Reputation: 10139

assignment in string

Here is my code and error message, and wondering in Python, if I want to assign the value of one character to the value of another character in a string, how to do it?

Error message:

    str[i] = str[i+1]
TypeError: 'str' object does not support item assignment

Source code:

class Solution(object):
    def RemoveDupCharacters(self, str):
        dic = {}
        for i in range(0,255):
            dic[i] = 0

        for i in range(len(str)):
            if dic[ord(str[i])] == 0:
                dic[ord(str[i])] = 1
            str[i] = str[i+1]
        return str

if __name__ == "__main__":
    s = Solution()
    print s.RemoveDupCharacters('aaaa')

Upvotes: 0

Views: 588

Answers (3)

Shawn Mehan
Shawn Mehan

Reputation: 4568

Using your code and reworking it to work with lists, one representation that works would be:

class Solution(object):

    def remove_dup_characters(self, input_string):
        letters = []
        s = []
        for c in input_string:
            if c not in letters:
                s.append(c)
                letters.append(c)
        return "".join(s)

    def remove_dup_characters2(selfself, input_string):
        return "".join(set(input_string))

if __name__ == "__main__":
    s = Solution()
    print s.remove_dup_characters('aaaabbaaa')
    print s.remove_dup_characters2('bbbbasdopiwerasdawera;lasoisdatatasdas')

which yields

ab
abedilopsrtw;

Upvotes: 1

James Mertz
James Mertz

Reputation: 8759

Since strings are immutable, you cannot inplace edit them. Instead use a list to dynamically edit things.

class Solution(object):
    def RemoveDupCharacters(self, str):
        temp_str = []
        for i in range(len(str)):
            if str[i] not in temp_str:
                temp_str.append(str[i])

        return ''.join(temp_str)

if __name__ == "__main__":
    s = Solution()
    print s.RemoveDupCharacters('aaaa')

Warning. The above solution will remove ALL duplicates of characters. for example:

s.RemoveDupCharacters('this is a quick test of removal')

yields:

this aquckeofrmvl

Note: if you're trying to remove duplicates, then this solution is more elegant.

Upvotes: 1

Chad S.
Chad S.

Reputation: 6633

You cannot assign the characters in a string. Strings are immutable. You can create a new string that has the characters you want, or you can use a data type which is mutable. For example, in this solution you can construct a list of characters in the string, then remove the duplicates, then reconstruct the string from the cleaned list.

Upvotes: 3

Related Questions