Randomly capitalize letters in string

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP











up vote
7
down vote

favorite












I want to randomly capitalize or lowercase each letter in a string. I'm new to working with strings in python, but I think because strings are immutable that I can't do the following:



i =0 
for c in sentence:
case = random.randint(0,1)
print("case = ", case)
if case == 0:
print("here0")
sentence[i] = sentence[i].lower()
else:
print("here1")
sentence[i] = sentence[i].upper()
i += 1
print ("new sentence = ", sentence)


And get the error: TypeError: 'str' object does not support item assignment



But then how else could I do this?










share|improve this question























  • Use another container, like a list, then create the string from that. Alternatively, create a new sting incrementally
    – juanpa.arrivillaga
    8 hours ago










  • You can always create a new String with randomized caps and small letters.
    – Mayank Porwal
    8 hours ago






  • 3




    Possible duplicate of How do I modify a single character in a string, in Python?
    – Sneftel
    2 hours ago














up vote
7
down vote

favorite












I want to randomly capitalize or lowercase each letter in a string. I'm new to working with strings in python, but I think because strings are immutable that I can't do the following:



i =0 
for c in sentence:
case = random.randint(0,1)
print("case = ", case)
if case == 0:
print("here0")
sentence[i] = sentence[i].lower()
else:
print("here1")
sentence[i] = sentence[i].upper()
i += 1
print ("new sentence = ", sentence)


And get the error: TypeError: 'str' object does not support item assignment



But then how else could I do this?










share|improve this question























  • Use another container, like a list, then create the string from that. Alternatively, create a new sting incrementally
    – juanpa.arrivillaga
    8 hours ago










  • You can always create a new String with randomized caps and small letters.
    – Mayank Porwal
    8 hours ago






  • 3




    Possible duplicate of How do I modify a single character in a string, in Python?
    – Sneftel
    2 hours ago












up vote
7
down vote

favorite









up vote
7
down vote

favorite











I want to randomly capitalize or lowercase each letter in a string. I'm new to working with strings in python, but I think because strings are immutable that I can't do the following:



i =0 
for c in sentence:
case = random.randint(0,1)
print("case = ", case)
if case == 0:
print("here0")
sentence[i] = sentence[i].lower()
else:
print("here1")
sentence[i] = sentence[i].upper()
i += 1
print ("new sentence = ", sentence)


And get the error: TypeError: 'str' object does not support item assignment



But then how else could I do this?










share|improve this question















I want to randomly capitalize or lowercase each letter in a string. I'm new to working with strings in python, but I think because strings are immutable that I can't do the following:



i =0 
for c in sentence:
case = random.randint(0,1)
print("case = ", case)
if case == 0:
print("here0")
sentence[i] = sentence[i].lower()
else:
print("here1")
sentence[i] = sentence[i].upper()
i += 1
print ("new sentence = ", sentence)


And get the error: TypeError: 'str' object does not support item assignment



But then how else could I do this?







python python-3.x uppercase lowercase






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 12 mins ago









Konrad Rudolph

388k1007641015




388k1007641015










asked 8 hours ago









user1045890

574




574











  • Use another container, like a list, then create the string from that. Alternatively, create a new sting incrementally
    – juanpa.arrivillaga
    8 hours ago










  • You can always create a new String with randomized caps and small letters.
    – Mayank Porwal
    8 hours ago






  • 3




    Possible duplicate of How do I modify a single character in a string, in Python?
    – Sneftel
    2 hours ago
















  • Use another container, like a list, then create the string from that. Alternatively, create a new sting incrementally
    – juanpa.arrivillaga
    8 hours ago










  • You can always create a new String with randomized caps and small letters.
    – Mayank Porwal
    8 hours ago






  • 3




    Possible duplicate of How do I modify a single character in a string, in Python?
    – Sneftel
    2 hours ago















Use another container, like a list, then create the string from that. Alternatively, create a new sting incrementally
– juanpa.arrivillaga
8 hours ago




Use another container, like a list, then create the string from that. Alternatively, create a new sting incrementally
– juanpa.arrivillaga
8 hours ago












You can always create a new String with randomized caps and small letters.
– Mayank Porwal
8 hours ago




You can always create a new String with randomized caps and small letters.
– Mayank Porwal
8 hours ago




3




3




Possible duplicate of How do I modify a single character in a string, in Python?
– Sneftel
2 hours ago




Possible duplicate of How do I modify a single character in a string, in Python?
– Sneftel
2 hours ago












7 Answers
7






active

oldest

votes

















up vote
15
down vote



accepted










You can use str.join with a generator expression like this:



from random import choice
sentence = 'Hello World'
print(''.join(choice((str.upper, str.lower))(c) for c in sentence))


Sample output:



heLlo WORLd





share|improve this answer
















  • 1




    No, list comprehension would be slower because it would materialize all item values first to form a list before passing the list to join, resulting in more overhead in both time and memory. With a generator expression, the join method would be able to simply iterate through the generator output as the generator produces item values one by one.
    – blhsing
    8 hours ago







  • 1




    Nice.., thanks for telling me
    – U9-Forward
    8 hours ago






  • 6




    @U9-Forward You are correct. join needs a list, so giving it a list in the first place is faster than giving it a generator. Authoritative reference.
    – timgeb
    8 hours ago






  • 1




    @timgeb Oh i am right, wow, now i know :-)
    – U9-Forward
    8 hours ago






  • 2




    @timgeb I stand corrected then. Thanks.
    – blhsing
    8 hours ago

















up vote
5
down vote













Build a new string.



Here's a solution with little changes to your original code:



>>> import random
>>>
>>> def randomcase(s):
...: result = ''
...: for c in s:
...: case = random.randint(0, 1)
...: if case == 0:
...: result += c.upper()
...: else:
...: result += c.lower()
...: return result
...:
...:
>>> randomcase('Hello Stackoverflow!')
>>> 'hElLo StaCkoVERFLow!'


edit: deleted my oneliners because I like blhsing's better.






share|improve this answer



























    up vote
    3
    down vote













    Just change the string implementation to a list implementation. As string is immutable, you cannot change the value inside the object. But Lists can be, So I've only changed that part of your code. And make note that there are much better ways to do this, Follow here



    import random
    sentence = "This is a test sentence" # Strings are immutable
    i =0
    new_sentence = # Lists are mutable sequences
    for c in sentence:
    case = random.randint(0,1)
    print("case = ", case)
    if case == 0:
    print("here0")
    new_sentence += sentence[i].lower() # append to the list
    else:
    print("here1")
    new_sentence += sentence[i].upper() # append to the list
    i += 1
    print ("new sentence = ", new_sentence)

    # to print as string
    new_sent = ''.join(new_sentence)
    print(new_sent)





    share|improve this answer





























      up vote
      2
      down vote













      sentence='quick test' 
      print(''.join([char.lower() if random.randint(0,1) else char.upper() for char in word ]))

      qUiCK TEsT





      share|improve this answer


















      • 1




        you can pass your list to ''join() for a more complete solution
        – Ev. Kounis
        8 hours ago

















      up vote
      1
      down vote













      You can do like below



      char_list = 
      for c in sentence:
      ucase = random.randint(0,1)
      print("case = ", case)
      if ucase:
      print("here1")
      char_list.append(c.upper())
      else:
      print("here0")
      char_list.append(c.lower())
      print ("new sentence = ", ''.join(char_list))





      share|improve this answer



























        up vote
        -1
        down vote













        One way without involving python loop would be sending it to numpy and do vectorized operation over that. For example:



        import numpy as np
        def randomCapitalize(s):
        s = np.array(s, 'c').view('u1')
        t = np.random.randint(0, 2, len(s), 'u1') # Temporary array
        t *= s != 32 # ASCII 32 (i.e. space) should not be lowercased
        t *= 32 # Decrease ASCII by 32 to lowercase
        s -= t
        return s.view('S' + str(len(s)))[0]
        randomCapitalize('hello world jfwojeo jaiofjowejfefjawivj a jofjawoefj')


        which outputs:



        b'HELLO WoRlD jFwoJEO JAioFjOWeJfEfJAWIvJ A JofjaWOefj'


        This solution should be reasonably fast especially for long string. There are two limitations of this method:



        • The input must be fully lower case. You can try .lower() it first but thats technically low efficient.


        • It need special care for non-a-to-z character. In the example above, only space is handled


        You can handle a lot more special characters at the same time by replacing



        t *= s != 32


        with



        # using space, enter, comma, period as example
        t *= np.isin(s, list(map(ord, ' n,.')), invert=True)


        For example:



        s = 'ascii table and description. ascii stands for american standard code for information interchange. computers can only understand numbers, so an ascii code is the numerical representation of a character such as'
        randomCapitalize(s)


        which outputs:



        b'ascII tABLe AnD descRiptIOn. ascii sTaNds for AmEricAN stanDaRD codE FOr InForMAtION iNTeRCHaNge. ComPUtERS can onLY UNdersTand nUMBers, So An asCIi COdE IS tHE nuMERIcaL rEPrEsEnTATion Of a CHaractEr such as'





        share|improve this answer



























          up vote
          -2
          down vote













          Use random.choice:



          from random import choice
          s = 'Hello World'
          print(''.join([choice((i.upper(),i.lower())) for i in s]))


          Output (random so no specific one):



          hELLo worLD





          share|improve this answer






















            Your Answer





            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            convertImagesToLinks: true,
            noModals: false,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













             

            draft saved


            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52942497%2frandomly-capitalize-letters-in-string%23new-answer', 'question_page');

            );

            Post as a guest






























            7 Answers
            7






            active

            oldest

            votes








            7 Answers
            7






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            15
            down vote



            accepted










            You can use str.join with a generator expression like this:



            from random import choice
            sentence = 'Hello World'
            print(''.join(choice((str.upper, str.lower))(c) for c in sentence))


            Sample output:



            heLlo WORLd





            share|improve this answer
















            • 1




              No, list comprehension would be slower because it would materialize all item values first to form a list before passing the list to join, resulting in more overhead in both time and memory. With a generator expression, the join method would be able to simply iterate through the generator output as the generator produces item values one by one.
              – blhsing
              8 hours ago







            • 1




              Nice.., thanks for telling me
              – U9-Forward
              8 hours ago






            • 6




              @U9-Forward You are correct. join needs a list, so giving it a list in the first place is faster than giving it a generator. Authoritative reference.
              – timgeb
              8 hours ago






            • 1




              @timgeb Oh i am right, wow, now i know :-)
              – U9-Forward
              8 hours ago






            • 2




              @timgeb I stand corrected then. Thanks.
              – blhsing
              8 hours ago














            up vote
            15
            down vote



            accepted










            You can use str.join with a generator expression like this:



            from random import choice
            sentence = 'Hello World'
            print(''.join(choice((str.upper, str.lower))(c) for c in sentence))


            Sample output:



            heLlo WORLd





            share|improve this answer
















            • 1




              No, list comprehension would be slower because it would materialize all item values first to form a list before passing the list to join, resulting in more overhead in both time and memory. With a generator expression, the join method would be able to simply iterate through the generator output as the generator produces item values one by one.
              – blhsing
              8 hours ago







            • 1




              Nice.., thanks for telling me
              – U9-Forward
              8 hours ago






            • 6




              @U9-Forward You are correct. join needs a list, so giving it a list in the first place is faster than giving it a generator. Authoritative reference.
              – timgeb
              8 hours ago






            • 1




              @timgeb Oh i am right, wow, now i know :-)
              – U9-Forward
              8 hours ago






            • 2




              @timgeb I stand corrected then. Thanks.
              – blhsing
              8 hours ago












            up vote
            15
            down vote



            accepted







            up vote
            15
            down vote



            accepted






            You can use str.join with a generator expression like this:



            from random import choice
            sentence = 'Hello World'
            print(''.join(choice((str.upper, str.lower))(c) for c in sentence))


            Sample output:



            heLlo WORLd





            share|improve this answer












            You can use str.join with a generator expression like this:



            from random import choice
            sentence = 'Hello World'
            print(''.join(choice((str.upper, str.lower))(c) for c in sentence))


            Sample output:



            heLlo WORLd






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered 8 hours ago









            blhsing

            23.7k41134




            23.7k41134







            • 1




              No, list comprehension would be slower because it would materialize all item values first to form a list before passing the list to join, resulting in more overhead in both time and memory. With a generator expression, the join method would be able to simply iterate through the generator output as the generator produces item values one by one.
              – blhsing
              8 hours ago







            • 1




              Nice.., thanks for telling me
              – U9-Forward
              8 hours ago






            • 6




              @U9-Forward You are correct. join needs a list, so giving it a list in the first place is faster than giving it a generator. Authoritative reference.
              – timgeb
              8 hours ago






            • 1




              @timgeb Oh i am right, wow, now i know :-)
              – U9-Forward
              8 hours ago






            • 2




              @timgeb I stand corrected then. Thanks.
              – blhsing
              8 hours ago












            • 1




              No, list comprehension would be slower because it would materialize all item values first to form a list before passing the list to join, resulting in more overhead in both time and memory. With a generator expression, the join method would be able to simply iterate through the generator output as the generator produces item values one by one.
              – blhsing
              8 hours ago







            • 1




              Nice.., thanks for telling me
              – U9-Forward
              8 hours ago






            • 6




              @U9-Forward You are correct. join needs a list, so giving it a list in the first place is faster than giving it a generator. Authoritative reference.
              – timgeb
              8 hours ago






            • 1




              @timgeb Oh i am right, wow, now i know :-)
              – U9-Forward
              8 hours ago






            • 2




              @timgeb I stand corrected then. Thanks.
              – blhsing
              8 hours ago







            1




            1




            No, list comprehension would be slower because it would materialize all item values first to form a list before passing the list to join, resulting in more overhead in both time and memory. With a generator expression, the join method would be able to simply iterate through the generator output as the generator produces item values one by one.
            – blhsing
            8 hours ago





            No, list comprehension would be slower because it would materialize all item values first to form a list before passing the list to join, resulting in more overhead in both time and memory. With a generator expression, the join method would be able to simply iterate through the generator output as the generator produces item values one by one.
            – blhsing
            8 hours ago





            1




            1




            Nice.., thanks for telling me
            – U9-Forward
            8 hours ago




            Nice.., thanks for telling me
            – U9-Forward
            8 hours ago




            6




            6




            @U9-Forward You are correct. join needs a list, so giving it a list in the first place is faster than giving it a generator. Authoritative reference.
            – timgeb
            8 hours ago




            @U9-Forward You are correct. join needs a list, so giving it a list in the first place is faster than giving it a generator. Authoritative reference.
            – timgeb
            8 hours ago




            1




            1




            @timgeb Oh i am right, wow, now i know :-)
            – U9-Forward
            8 hours ago




            @timgeb Oh i am right, wow, now i know :-)
            – U9-Forward
            8 hours ago




            2




            2




            @timgeb I stand corrected then. Thanks.
            – blhsing
            8 hours ago




            @timgeb I stand corrected then. Thanks.
            – blhsing
            8 hours ago












            up vote
            5
            down vote













            Build a new string.



            Here's a solution with little changes to your original code:



            >>> import random
            >>>
            >>> def randomcase(s):
            ...: result = ''
            ...: for c in s:
            ...: case = random.randint(0, 1)
            ...: if case == 0:
            ...: result += c.upper()
            ...: else:
            ...: result += c.lower()
            ...: return result
            ...:
            ...:
            >>> randomcase('Hello Stackoverflow!')
            >>> 'hElLo StaCkoVERFLow!'


            edit: deleted my oneliners because I like blhsing's better.






            share|improve this answer
























              up vote
              5
              down vote













              Build a new string.



              Here's a solution with little changes to your original code:



              >>> import random
              >>>
              >>> def randomcase(s):
              ...: result = ''
              ...: for c in s:
              ...: case = random.randint(0, 1)
              ...: if case == 0:
              ...: result += c.upper()
              ...: else:
              ...: result += c.lower()
              ...: return result
              ...:
              ...:
              >>> randomcase('Hello Stackoverflow!')
              >>> 'hElLo StaCkoVERFLow!'


              edit: deleted my oneliners because I like blhsing's better.






              share|improve this answer






















                up vote
                5
                down vote










                up vote
                5
                down vote









                Build a new string.



                Here's a solution with little changes to your original code:



                >>> import random
                >>>
                >>> def randomcase(s):
                ...: result = ''
                ...: for c in s:
                ...: case = random.randint(0, 1)
                ...: if case == 0:
                ...: result += c.upper()
                ...: else:
                ...: result += c.lower()
                ...: return result
                ...:
                ...:
                >>> randomcase('Hello Stackoverflow!')
                >>> 'hElLo StaCkoVERFLow!'


                edit: deleted my oneliners because I like blhsing's better.






                share|improve this answer












                Build a new string.



                Here's a solution with little changes to your original code:



                >>> import random
                >>>
                >>> def randomcase(s):
                ...: result = ''
                ...: for c in s:
                ...: case = random.randint(0, 1)
                ...: if case == 0:
                ...: result += c.upper()
                ...: else:
                ...: result += c.lower()
                ...: return result
                ...:
                ...:
                >>> randomcase('Hello Stackoverflow!')
                >>> 'hElLo StaCkoVERFLow!'


                edit: deleted my oneliners because I like blhsing's better.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered 8 hours ago









                timgeb

                39.4k105278




                39.4k105278




















                    up vote
                    3
                    down vote













                    Just change the string implementation to a list implementation. As string is immutable, you cannot change the value inside the object. But Lists can be, So I've only changed that part of your code. And make note that there are much better ways to do this, Follow here



                    import random
                    sentence = "This is a test sentence" # Strings are immutable
                    i =0
                    new_sentence = # Lists are mutable sequences
                    for c in sentence:
                    case = random.randint(0,1)
                    print("case = ", case)
                    if case == 0:
                    print("here0")
                    new_sentence += sentence[i].lower() # append to the list
                    else:
                    print("here1")
                    new_sentence += sentence[i].upper() # append to the list
                    i += 1
                    print ("new sentence = ", new_sentence)

                    # to print as string
                    new_sent = ''.join(new_sentence)
                    print(new_sent)





                    share|improve this answer


























                      up vote
                      3
                      down vote













                      Just change the string implementation to a list implementation. As string is immutable, you cannot change the value inside the object. But Lists can be, So I've only changed that part of your code. And make note that there are much better ways to do this, Follow here



                      import random
                      sentence = "This is a test sentence" # Strings are immutable
                      i =0
                      new_sentence = # Lists are mutable sequences
                      for c in sentence:
                      case = random.randint(0,1)
                      print("case = ", case)
                      if case == 0:
                      print("here0")
                      new_sentence += sentence[i].lower() # append to the list
                      else:
                      print("here1")
                      new_sentence += sentence[i].upper() # append to the list
                      i += 1
                      print ("new sentence = ", new_sentence)

                      # to print as string
                      new_sent = ''.join(new_sentence)
                      print(new_sent)





                      share|improve this answer
























                        up vote
                        3
                        down vote










                        up vote
                        3
                        down vote









                        Just change the string implementation to a list implementation. As string is immutable, you cannot change the value inside the object. But Lists can be, So I've only changed that part of your code. And make note that there are much better ways to do this, Follow here



                        import random
                        sentence = "This is a test sentence" # Strings are immutable
                        i =0
                        new_sentence = # Lists are mutable sequences
                        for c in sentence:
                        case = random.randint(0,1)
                        print("case = ", case)
                        if case == 0:
                        print("here0")
                        new_sentence += sentence[i].lower() # append to the list
                        else:
                        print("here1")
                        new_sentence += sentence[i].upper() # append to the list
                        i += 1
                        print ("new sentence = ", new_sentence)

                        # to print as string
                        new_sent = ''.join(new_sentence)
                        print(new_sent)





                        share|improve this answer














                        Just change the string implementation to a list implementation. As string is immutable, you cannot change the value inside the object. But Lists can be, So I've only changed that part of your code. And make note that there are much better ways to do this, Follow here



                        import random
                        sentence = "This is a test sentence" # Strings are immutable
                        i =0
                        new_sentence = # Lists are mutable sequences
                        for c in sentence:
                        case = random.randint(0,1)
                        print("case = ", case)
                        if case == 0:
                        print("here0")
                        new_sentence += sentence[i].lower() # append to the list
                        else:
                        print("here1")
                        new_sentence += sentence[i].upper() # append to the list
                        i += 1
                        print ("new sentence = ", new_sentence)

                        # to print as string
                        new_sent = ''.join(new_sentence)
                        print(new_sent)






                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited 8 hours ago

























                        answered 8 hours ago









                        Vineeth Sai

                        1,46211019




                        1,46211019




















                            up vote
                            2
                            down vote













                            sentence='quick test' 
                            print(''.join([char.lower() if random.randint(0,1) else char.upper() for char in word ]))

                            qUiCK TEsT





                            share|improve this answer


















                            • 1




                              you can pass your list to ''join() for a more complete solution
                              – Ev. Kounis
                              8 hours ago














                            up vote
                            2
                            down vote













                            sentence='quick test' 
                            print(''.join([char.lower() if random.randint(0,1) else char.upper() for char in word ]))

                            qUiCK TEsT





                            share|improve this answer


















                            • 1




                              you can pass your list to ''join() for a more complete solution
                              – Ev. Kounis
                              8 hours ago












                            up vote
                            2
                            down vote










                            up vote
                            2
                            down vote









                            sentence='quick test' 
                            print(''.join([char.lower() if random.randint(0,1) else char.upper() for char in word ]))

                            qUiCK TEsT





                            share|improve this answer














                            sentence='quick test' 
                            print(''.join([char.lower() if random.randint(0,1) else char.upper() for char in word ]))

                            qUiCK TEsT






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited 8 hours ago

























                            answered 8 hours ago









                            AILearning

                            149111




                            149111







                            • 1




                              you can pass your list to ''join() for a more complete solution
                              – Ev. Kounis
                              8 hours ago












                            • 1




                              you can pass your list to ''join() for a more complete solution
                              – Ev. Kounis
                              8 hours ago







                            1




                            1




                            you can pass your list to ''join() for a more complete solution
                            – Ev. Kounis
                            8 hours ago




                            you can pass your list to ''join() for a more complete solution
                            – Ev. Kounis
                            8 hours ago










                            up vote
                            1
                            down vote













                            You can do like below



                            char_list = 
                            for c in sentence:
                            ucase = random.randint(0,1)
                            print("case = ", case)
                            if ucase:
                            print("here1")
                            char_list.append(c.upper())
                            else:
                            print("here0")
                            char_list.append(c.lower())
                            print ("new sentence = ", ''.join(char_list))





                            share|improve this answer
























                              up vote
                              1
                              down vote













                              You can do like below



                              char_list = 
                              for c in sentence:
                              ucase = random.randint(0,1)
                              print("case = ", case)
                              if ucase:
                              print("here1")
                              char_list.append(c.upper())
                              else:
                              print("here0")
                              char_list.append(c.lower())
                              print ("new sentence = ", ''.join(char_list))





                              share|improve this answer






















                                up vote
                                1
                                down vote










                                up vote
                                1
                                down vote









                                You can do like below



                                char_list = 
                                for c in sentence:
                                ucase = random.randint(0,1)
                                print("case = ", case)
                                if ucase:
                                print("here1")
                                char_list.append(c.upper())
                                else:
                                print("here0")
                                char_list.append(c.lower())
                                print ("new sentence = ", ''.join(char_list))





                                share|improve this answer












                                You can do like below



                                char_list = 
                                for c in sentence:
                                ucase = random.randint(0,1)
                                print("case = ", case)
                                if ucase:
                                print("here1")
                                char_list.append(c.upper())
                                else:
                                print("here0")
                                char_list.append(c.lower())
                                print ("new sentence = ", ''.join(char_list))






                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered 8 hours ago









                                ansu5555

                                1816




                                1816




















                                    up vote
                                    -1
                                    down vote













                                    One way without involving python loop would be sending it to numpy and do vectorized operation over that. For example:



                                    import numpy as np
                                    def randomCapitalize(s):
                                    s = np.array(s, 'c').view('u1')
                                    t = np.random.randint(0, 2, len(s), 'u1') # Temporary array
                                    t *= s != 32 # ASCII 32 (i.e. space) should not be lowercased
                                    t *= 32 # Decrease ASCII by 32 to lowercase
                                    s -= t
                                    return s.view('S' + str(len(s)))[0]
                                    randomCapitalize('hello world jfwojeo jaiofjowejfefjawivj a jofjawoefj')


                                    which outputs:



                                    b'HELLO WoRlD jFwoJEO JAioFjOWeJfEfJAWIvJ A JofjaWOefj'


                                    This solution should be reasonably fast especially for long string. There are two limitations of this method:



                                    • The input must be fully lower case. You can try .lower() it first but thats technically low efficient.


                                    • It need special care for non-a-to-z character. In the example above, only space is handled


                                    You can handle a lot more special characters at the same time by replacing



                                    t *= s != 32


                                    with



                                    # using space, enter, comma, period as example
                                    t *= np.isin(s, list(map(ord, ' n,.')), invert=True)


                                    For example:



                                    s = 'ascii table and description. ascii stands for american standard code for information interchange. computers can only understand numbers, so an ascii code is the numerical representation of a character such as'
                                    randomCapitalize(s)


                                    which outputs:



                                    b'ascII tABLe AnD descRiptIOn. ascii sTaNds for AmEricAN stanDaRD codE FOr InForMAtION iNTeRCHaNge. ComPUtERS can onLY UNdersTand nUMBers, So An asCIi COdE IS tHE nuMERIcaL rEPrEsEnTATion Of a CHaractEr such as'





                                    share|improve this answer
























                                      up vote
                                      -1
                                      down vote













                                      One way without involving python loop would be sending it to numpy and do vectorized operation over that. For example:



                                      import numpy as np
                                      def randomCapitalize(s):
                                      s = np.array(s, 'c').view('u1')
                                      t = np.random.randint(0, 2, len(s), 'u1') # Temporary array
                                      t *= s != 32 # ASCII 32 (i.e. space) should not be lowercased
                                      t *= 32 # Decrease ASCII by 32 to lowercase
                                      s -= t
                                      return s.view('S' + str(len(s)))[0]
                                      randomCapitalize('hello world jfwojeo jaiofjowejfefjawivj a jofjawoefj')


                                      which outputs:



                                      b'HELLO WoRlD jFwoJEO JAioFjOWeJfEfJAWIvJ A JofjaWOefj'


                                      This solution should be reasonably fast especially for long string. There are two limitations of this method:



                                      • The input must be fully lower case. You can try .lower() it first but thats technically low efficient.


                                      • It need special care for non-a-to-z character. In the example above, only space is handled


                                      You can handle a lot more special characters at the same time by replacing



                                      t *= s != 32


                                      with



                                      # using space, enter, comma, period as example
                                      t *= np.isin(s, list(map(ord, ' n,.')), invert=True)


                                      For example:



                                      s = 'ascii table and description. ascii stands for american standard code for information interchange. computers can only understand numbers, so an ascii code is the numerical representation of a character such as'
                                      randomCapitalize(s)


                                      which outputs:



                                      b'ascII tABLe AnD descRiptIOn. ascii sTaNds for AmEricAN stanDaRD codE FOr InForMAtION iNTeRCHaNge. ComPUtERS can onLY UNdersTand nUMBers, So An asCIi COdE IS tHE nuMERIcaL rEPrEsEnTATion Of a CHaractEr such as'





                                      share|improve this answer






















                                        up vote
                                        -1
                                        down vote










                                        up vote
                                        -1
                                        down vote









                                        One way without involving python loop would be sending it to numpy and do vectorized operation over that. For example:



                                        import numpy as np
                                        def randomCapitalize(s):
                                        s = np.array(s, 'c').view('u1')
                                        t = np.random.randint(0, 2, len(s), 'u1') # Temporary array
                                        t *= s != 32 # ASCII 32 (i.e. space) should not be lowercased
                                        t *= 32 # Decrease ASCII by 32 to lowercase
                                        s -= t
                                        return s.view('S' + str(len(s)))[0]
                                        randomCapitalize('hello world jfwojeo jaiofjowejfefjawivj a jofjawoefj')


                                        which outputs:



                                        b'HELLO WoRlD jFwoJEO JAioFjOWeJfEfJAWIvJ A JofjaWOefj'


                                        This solution should be reasonably fast especially for long string. There are two limitations of this method:



                                        • The input must be fully lower case. You can try .lower() it first but thats technically low efficient.


                                        • It need special care for non-a-to-z character. In the example above, only space is handled


                                        You can handle a lot more special characters at the same time by replacing



                                        t *= s != 32


                                        with



                                        # using space, enter, comma, period as example
                                        t *= np.isin(s, list(map(ord, ' n,.')), invert=True)


                                        For example:



                                        s = 'ascii table and description. ascii stands for american standard code for information interchange. computers can only understand numbers, so an ascii code is the numerical representation of a character such as'
                                        randomCapitalize(s)


                                        which outputs:



                                        b'ascII tABLe AnD descRiptIOn. ascii sTaNds for AmEricAN stanDaRD codE FOr InForMAtION iNTeRCHaNge. ComPUtERS can onLY UNdersTand nUMBers, So An asCIi COdE IS tHE nuMERIcaL rEPrEsEnTATion Of a CHaractEr such as'





                                        share|improve this answer












                                        One way without involving python loop would be sending it to numpy and do vectorized operation over that. For example:



                                        import numpy as np
                                        def randomCapitalize(s):
                                        s = np.array(s, 'c').view('u1')
                                        t = np.random.randint(0, 2, len(s), 'u1') # Temporary array
                                        t *= s != 32 # ASCII 32 (i.e. space) should not be lowercased
                                        t *= 32 # Decrease ASCII by 32 to lowercase
                                        s -= t
                                        return s.view('S' + str(len(s)))[0]
                                        randomCapitalize('hello world jfwojeo jaiofjowejfefjawivj a jofjawoefj')


                                        which outputs:



                                        b'HELLO WoRlD jFwoJEO JAioFjOWeJfEfJAWIvJ A JofjaWOefj'


                                        This solution should be reasonably fast especially for long string. There are two limitations of this method:



                                        • The input must be fully lower case. You can try .lower() it first but thats technically low efficient.


                                        • It need special care for non-a-to-z character. In the example above, only space is handled


                                        You can handle a lot more special characters at the same time by replacing



                                        t *= s != 32


                                        with



                                        # using space, enter, comma, period as example
                                        t *= np.isin(s, list(map(ord, ' n,.')), invert=True)


                                        For example:



                                        s = 'ascii table and description. ascii stands for american standard code for information interchange. computers can only understand numbers, so an ascii code is the numerical representation of a character such as'
                                        randomCapitalize(s)


                                        which outputs:



                                        b'ascII tABLe AnD descRiptIOn. ascii sTaNds for AmEricAN stanDaRD codE FOr InForMAtION iNTeRCHaNge. ComPUtERS can onLY UNdersTand nUMBers, So An asCIi COdE IS tHE nuMERIcaL rEPrEsEnTATion Of a CHaractEr such as'






                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered 8 hours ago









                                        ZisIsNotZis

                                        99211




                                        99211




















                                            up vote
                                            -2
                                            down vote













                                            Use random.choice:



                                            from random import choice
                                            s = 'Hello World'
                                            print(''.join([choice((i.upper(),i.lower())) for i in s]))


                                            Output (random so no specific one):



                                            hELLo worLD





                                            share|improve this answer


























                                              up vote
                                              -2
                                              down vote













                                              Use random.choice:



                                              from random import choice
                                              s = 'Hello World'
                                              print(''.join([choice((i.upper(),i.lower())) for i in s]))


                                              Output (random so no specific one):



                                              hELLo worLD





                                              share|improve this answer
























                                                up vote
                                                -2
                                                down vote










                                                up vote
                                                -2
                                                down vote









                                                Use random.choice:



                                                from random import choice
                                                s = 'Hello World'
                                                print(''.join([choice((i.upper(),i.lower())) for i in s]))


                                                Output (random so no specific one):



                                                hELLo worLD





                                                share|improve this answer














                                                Use random.choice:



                                                from random import choice
                                                s = 'Hello World'
                                                print(''.join([choice((i.upper(),i.lower())) for i in s]))


                                                Output (random so no specific one):



                                                hELLo worLD






                                                share|improve this answer














                                                share|improve this answer



                                                share|improve this answer








                                                edited 8 hours ago

























                                                answered 8 hours ago









                                                U9-Forward

                                                7,5272730




                                                7,5272730



























                                                     

                                                    draft saved


                                                    draft discarded















































                                                     


                                                    draft saved


                                                    draft discarded














                                                    StackExchange.ready(
                                                    function ()
                                                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52942497%2frandomly-capitalize-letters-in-string%23new-answer', 'question_page');

                                                    );

                                                    Post as a guest













































































                                                    Comments

                                                    Popular posts from this blog

                                                    Long meetings (6-7 hours a day): Being “babysat” by supervisor

                                                    Is the Concept of Multiple Fantasy Races Scientifically Flawed? [closed]

                                                    Confectionery