Python Forum
string to list and back again as same type
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
string to list and back again as same type
#8
Don't know what you are doing.
class ListString:
    def __init__(self, string):
        self.type = type(string)
        self.string = list(string)

    def __getitem__(self, index):
        return self.string[index]

    def __setitem__(self, index, value):
        self.string[index] = value

    def __len__(self):
        return len(self.string)

    def __bool__(self):
        return len(self) > 0

    def __str__(self):
        return str(self.string)

    def get_string(self):
        if self.type == str:
            return ''.join(self.string)
        return self.type(self.string)

a = ListString('string')
print(a)
print(a.get_string())

a = ListString(b'bytes')
print(a)
print(a.get_string())

a = ListString(bytearray(b'bytearray'))
print(a)
print(a.get_string())
99 percent of computer problems exists between chair and keyboard.
Reply


Messages In This Thread
RE: string to list and back again as same type - by Windspar - Sep-05-2018, 11:46 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  No matter what I do I get back "List indices must be integers or slices, not list" Radical 4 1,445 Sep-24-2023, 05:03 AM
Last Post: deanhystad
  reading a table which is of type string saisankalpj 2 1,066 Dec-03-2022, 11:19 AM
Last Post: saisankalpj
  search a list or tuple for a specific type ot class Skaperen 8 2,180 Jul-22-2022, 10:29 PM
Last Post: Skaperen
  TypeError: unsupported opperand type(s) for %: 'int' and 'list' cool_person 7 2,450 May-07-2022, 08:40 AM
Last Post: ibreeden
  unsupported operand type(s) for %: 'list' and 'int' RandomCoder 4 33,233 May-07-2022, 08:07 AM
Last Post: menator01
  You have any idea, how fix TypeError: unhashable type: 'list' lsepolis123 2 3,192 Jun-02-2021, 07:55 AM
Last Post: supuflounder
  TypeError: __str__ returned non-string (type tuple) Anldra12 1 7,567 Apr-13-2021, 07:50 AM
Last Post: Anldra12
  What type of *data* is the name of a list/tuple/dict, etc? alloydog 9 4,750 Jan-30-2021, 07:11 AM
Last Post: alloydog
Question dict value, how to change type from int to list? swissjoker 3 2,959 Dec-09-2020, 09:50 AM
Last Post: perfringo
  Make list of dates between today back to n days Mekala 3 2,524 Oct-03-2020, 01:01 PM
Last Post: ibreeden

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020