0

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')
matsjoyce
  • 5,744
  • 6
  • 31
  • 38
Lin Ma
  • 9,739
  • 32
  • 105
  • 175
  • 1
    Do you mean that if you have string "ab" then you want to make it "bb" or "aa"? – MohitC Sep 28 '15 at 20:57
  • 2
    Like the error says, you can't do this; strings are immutable. – Daniel Roseman Sep 28 '15 at 21:00
  • 3
    You cannot do assignment with strings as they are immutable, you can use a list storing the string as a list of characters and then call join on the list to get the string back – Padraic Cunningham Sep 28 '15 at 21:00
  • 1
    What are you actually trying to do? – Padraic Cunningham Sep 28 '15 at 21:02
  • 3
    I think that this is what you're trying to do: http://stackoverflow.com/questions/9841303/removing-duplicate-characters-from-a-string – James Mertz Sep 28 '15 at 21:03
  • 1
    Even if you could assign your code would just return the same string when you pass it a string of duplicate characters – Padraic Cunningham Sep 28 '15 at 21:07
  • @PadraicCunningham, how do use a list for string, could you show me? And in Python, is it possible to do in-place without create new string? – Lin Ma Sep 28 '15 at 21:11
  • @MohitChandak, yes, I want to change the content (characters) of string, appreciate if you could point me the solution. And in Python, is it possible to do in-place without create new string? Thanks. – Lin Ma Sep 28 '15 at 21:12
  • 1
    @LinMa, your code does not really make sense for just removing duplicates, what is the dict for and why are you using ord? – Padraic Cunningham Sep 28 '15 at 21:14
  • 1
    You cannot modify a string inplace, if you could it would not be immutable, is there more to your question than simply doing `"".join(set(s))`? – Padraic Cunningham Sep 28 '15 at 21:15
  • @PadraicCunningham, then how do we do in-place operation of strings in Python, using some other kinds of data structure? – Lin Ma Sep 28 '15 at 21:17
  • 1
    You can place each character in a list i.e `list(s)` modify with assignment or whatever else you want and call `"".join(lst)` on the list to get a string. You can `+=` a string but it still creates a new string/object – Padraic Cunningham Sep 28 '15 at 21:18
  • @PadraicCunningham, thanks for the info, how to create a list represents a string? Appreciate if you could show me an example? Thanks. – Lin Ma Sep 28 '15 at 21:20
  • literally `lst = list(your_string)` `list("foo") -> ["f","o","o"]` – Padraic Cunningham Sep 28 '15 at 21:20
  • @PadraicCunningham, it works! Cool. If you could help to add a reply, I will mark it as answered so that more people are benefit from the community. :) – Lin Ma Sep 28 '15 at 21:24
  • @LinMa, you can add an answer yourself with the code that worked for you and accept the answer, you will get a bit more rep for yourself ;) – Padraic Cunningham Sep 28 '15 at 21:30
  • Not sure what the goal is but map and enumerate might be useful http://pastebin.com/nK1wXqCk, you should be aware your code will index error when you get to the last char using + 1 as the index will be outside the range of your list – Padraic Cunningham Sep 28 '15 at 21:35

3 Answers3

3

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.

Chad S.
  • 6,252
  • 15
  • 25
1

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.

Community
  • 1
  • 1
James Mertz
  • 8,459
  • 11
  • 60
  • 87
1

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;
Shawn Mehan
  • 4,513
  • 9
  • 31
  • 51
  • thanks for the response, is it possible to do kinds of in-place operation to avoid create a new string for space efficiency? – Lin Ma Sep 28 '15 at 21:18
  • There is no way to affect the original string, @Lin Ma. That's what we mean when we say the string is **immutable**. But I have added another def which might give you better performance for large strings. ymmv. – Shawn Mehan Sep 28 '15 at 21:46