0

I'm trying to change characters from x into upper or lower character depending whether they are in r or c. And the problem is that i can't get all the changed characters into one string.

import unittest

def fun_exercise_6(x):
    y = []
    r = 'abcdefghijkl'
    c = 'mnopqrstuvwxz'
    for i in range(len(x)):
        if(x[i] in r):
            y += x[i].lower()
        elif(x[i] in c):
            y += x[i].upper()
    return y


class TestAssignment1(unittest.TestCase):
    def test1_exercise_6(self):
        self.assertTrue(fun_exercise_6("osso") == "OSSO")
    def test2_exercise_6(self):
        self.assertTrue(fun_exercise_6("goat") == "gOaT")
    def test3_exercise_6(self):
        self.assertTrue(fun_exercise_6("bag") == "bag")
    def test4_exercise_6(self):
        self.assertTrue(fun_exercise_6("boat") == "bOaT" )

if __name__ == '__main__':
    unittest.main()

3 Answers 3

1

Using a list as you are using is probably the best approach while you are figuring out whether or not each character should be uppered or lowered. You can join your list using str's join method. In your case, you could have your return statement look like this:

return ''.join(y)

What this would do is join a collection of strings (your individual characters into one new string using the string you join on ('').

For example, ''.join(['a', 'b', 'c']) will turn into 'abc'

This is a much better solution than making y a string as strings are immutable data types. If you make y a string when you are constructing it, you would have to redefine and reallocate the ENTIRE string each time you appended a character. Using a list, as you are doing, and joining it at the end would allow you to accumulate the characters and then join them all at once, which is comparatively very efficient.

Sign up to request clarification or add additional context in comments.

Comments

0

If you define y as an empty string y = "" instead of an empty list you will get y as one string. Since when you declare y = [] and add an item to the list, you add a string to a list of string not a character to a string.

Comments

0

You can't compare a list and a string.

"abc" == ["a", "b", "c'] # False

The initial value of y in the fun_exercise_6 function must be ""

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.