How to capitalize specific letters in a string given certain rules












2














I am massaging strings so that the 1st letter of the string and the first letter following either a dash or a slash needs to be capitalized.



So the following string:



test/string - this is a test string



Should look look like so:



Test/String - This is a test string



So in trying to solve this problem my 1st idea seems like a bad idea - iterate the string and check every character and using indexing etc. determine if a character follows a dash or slash, if it does set it to upper and write out to my new string.



def correct_sentence_case(test_phrase):

corrected_test_phrase = ''

firstLetter = True

for char in test_phrase:

if firstLetter:

corrected_test_phrase += char.upper()

firstLetter = False

#elif char == '/':
else:

corrected_test_phrase += char


This just seems VERY un-pythonic. What is a pythonic way to handle this?



Something along the lines of the following would be awesome but I can't pass in both a dash and a slash to the split:



corrected_test_phrase = ' - '.join(i.capitalize() for i in test_phrase.split(' - '))


Which I got from this SO:



Convert UPPERCASE string to sentence case in Python



Any help will be appreciated :)










share|improve this question
























  • Why doesn't your "wanted way" work? Split, capitalize and join
    – SimonF
    Dec 27 '18 at 20:21












  • @SimonF Because it doesn't produce Test/String - This is a test string but Test/string - This is a test string
    – BoarGules
    Dec 27 '18 at 20:24










  • @SimonF - It works super nicely but I can't pass both dashes and slashes to the split - I probably should have said that in my question - it is unclear - ty
    – beginAgain
    Dec 27 '18 at 20:25






  • 1




    Explicit is better than implicit. Simple is better than complex. Sparse is better than dense. Readability counts.; do it in more than one step.
    – Pedro Rodrigues
    Dec 27 '18 at 20:27








  • 1




    You have two different criteria for splitting. The one delimiter is " - " and the other is "". Do your split/capitalize in 2 passes. Split first on " - " into a list and then split every element of that list on "".
    – BoarGules
    Dec 27 '18 at 20:27
















2














I am massaging strings so that the 1st letter of the string and the first letter following either a dash or a slash needs to be capitalized.



So the following string:



test/string - this is a test string



Should look look like so:



Test/String - This is a test string



So in trying to solve this problem my 1st idea seems like a bad idea - iterate the string and check every character and using indexing etc. determine if a character follows a dash or slash, if it does set it to upper and write out to my new string.



def correct_sentence_case(test_phrase):

corrected_test_phrase = ''

firstLetter = True

for char in test_phrase:

if firstLetter:

corrected_test_phrase += char.upper()

firstLetter = False

#elif char == '/':
else:

corrected_test_phrase += char


This just seems VERY un-pythonic. What is a pythonic way to handle this?



Something along the lines of the following would be awesome but I can't pass in both a dash and a slash to the split:



corrected_test_phrase = ' - '.join(i.capitalize() for i in test_phrase.split(' - '))


Which I got from this SO:



Convert UPPERCASE string to sentence case in Python



Any help will be appreciated :)










share|improve this question
























  • Why doesn't your "wanted way" work? Split, capitalize and join
    – SimonF
    Dec 27 '18 at 20:21












  • @SimonF Because it doesn't produce Test/String - This is a test string but Test/string - This is a test string
    – BoarGules
    Dec 27 '18 at 20:24










  • @SimonF - It works super nicely but I can't pass both dashes and slashes to the split - I probably should have said that in my question - it is unclear - ty
    – beginAgain
    Dec 27 '18 at 20:25






  • 1




    Explicit is better than implicit. Simple is better than complex. Sparse is better than dense. Readability counts.; do it in more than one step.
    – Pedro Rodrigues
    Dec 27 '18 at 20:27








  • 1




    You have two different criteria for splitting. The one delimiter is " - " and the other is "". Do your split/capitalize in 2 passes. Split first on " - " into a list and then split every element of that list on "".
    – BoarGules
    Dec 27 '18 at 20:27














2












2








2







I am massaging strings so that the 1st letter of the string and the first letter following either a dash or a slash needs to be capitalized.



So the following string:



test/string - this is a test string



Should look look like so:



Test/String - This is a test string



So in trying to solve this problem my 1st idea seems like a bad idea - iterate the string and check every character and using indexing etc. determine if a character follows a dash or slash, if it does set it to upper and write out to my new string.



def correct_sentence_case(test_phrase):

corrected_test_phrase = ''

firstLetter = True

for char in test_phrase:

if firstLetter:

corrected_test_phrase += char.upper()

firstLetter = False

#elif char == '/':
else:

corrected_test_phrase += char


This just seems VERY un-pythonic. What is a pythonic way to handle this?



Something along the lines of the following would be awesome but I can't pass in both a dash and a slash to the split:



corrected_test_phrase = ' - '.join(i.capitalize() for i in test_phrase.split(' - '))


Which I got from this SO:



Convert UPPERCASE string to sentence case in Python



Any help will be appreciated :)










share|improve this question















I am massaging strings so that the 1st letter of the string and the first letter following either a dash or a slash needs to be capitalized.



So the following string:



test/string - this is a test string



Should look look like so:



Test/String - This is a test string



So in trying to solve this problem my 1st idea seems like a bad idea - iterate the string and check every character and using indexing etc. determine if a character follows a dash or slash, if it does set it to upper and write out to my new string.



def correct_sentence_case(test_phrase):

corrected_test_phrase = ''

firstLetter = True

for char in test_phrase:

if firstLetter:

corrected_test_phrase += char.upper()

firstLetter = False

#elif char == '/':
else:

corrected_test_phrase += char


This just seems VERY un-pythonic. What is a pythonic way to handle this?



Something along the lines of the following would be awesome but I can't pass in both a dash and a slash to the split:



corrected_test_phrase = ' - '.join(i.capitalize() for i in test_phrase.split(' - '))


Which I got from this SO:



Convert UPPERCASE string to sentence case in Python



Any help will be appreciated :)







python string






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 27 '18 at 20:26

























asked Dec 27 '18 at 20:17









beginAgain

10410




10410












  • Why doesn't your "wanted way" work? Split, capitalize and join
    – SimonF
    Dec 27 '18 at 20:21












  • @SimonF Because it doesn't produce Test/String - This is a test string but Test/string - This is a test string
    – BoarGules
    Dec 27 '18 at 20:24










  • @SimonF - It works super nicely but I can't pass both dashes and slashes to the split - I probably should have said that in my question - it is unclear - ty
    – beginAgain
    Dec 27 '18 at 20:25






  • 1




    Explicit is better than implicit. Simple is better than complex. Sparse is better than dense. Readability counts.; do it in more than one step.
    – Pedro Rodrigues
    Dec 27 '18 at 20:27








  • 1




    You have two different criteria for splitting. The one delimiter is " - " and the other is "". Do your split/capitalize in 2 passes. Split first on " - " into a list and then split every element of that list on "".
    – BoarGules
    Dec 27 '18 at 20:27


















  • Why doesn't your "wanted way" work? Split, capitalize and join
    – SimonF
    Dec 27 '18 at 20:21












  • @SimonF Because it doesn't produce Test/String - This is a test string but Test/string - This is a test string
    – BoarGules
    Dec 27 '18 at 20:24










  • @SimonF - It works super nicely but I can't pass both dashes and slashes to the split - I probably should have said that in my question - it is unclear - ty
    – beginAgain
    Dec 27 '18 at 20:25






  • 1




    Explicit is better than implicit. Simple is better than complex. Sparse is better than dense. Readability counts.; do it in more than one step.
    – Pedro Rodrigues
    Dec 27 '18 at 20:27








  • 1




    You have two different criteria for splitting. The one delimiter is " - " and the other is "". Do your split/capitalize in 2 passes. Split first on " - " into a list and then split every element of that list on "".
    – BoarGules
    Dec 27 '18 at 20:27
















Why doesn't your "wanted way" work? Split, capitalize and join
– SimonF
Dec 27 '18 at 20:21






Why doesn't your "wanted way" work? Split, capitalize and join
– SimonF
Dec 27 '18 at 20:21














@SimonF Because it doesn't produce Test/String - This is a test string but Test/string - This is a test string
– BoarGules
Dec 27 '18 at 20:24




@SimonF Because it doesn't produce Test/String - This is a test string but Test/string - This is a test string
– BoarGules
Dec 27 '18 at 20:24












@SimonF - It works super nicely but I can't pass both dashes and slashes to the split - I probably should have said that in my question - it is unclear - ty
– beginAgain
Dec 27 '18 at 20:25




@SimonF - It works super nicely but I can't pass both dashes and slashes to the split - I probably should have said that in my question - it is unclear - ty
– beginAgain
Dec 27 '18 at 20:25




1




1




Explicit is better than implicit. Simple is better than complex. Sparse is better than dense. Readability counts.; do it in more than one step.
– Pedro Rodrigues
Dec 27 '18 at 20:27






Explicit is better than implicit. Simple is better than complex. Sparse is better than dense. Readability counts.; do it in more than one step.
– Pedro Rodrigues
Dec 27 '18 at 20:27






1




1




You have two different criteria for splitting. The one delimiter is " - " and the other is "". Do your split/capitalize in 2 passes. Split first on " - " into a list and then split every element of that list on "".
– BoarGules
Dec 27 '18 at 20:27




You have two different criteria for splitting. The one delimiter is " - " and the other is "". Do your split/capitalize in 2 passes. Split first on " - " into a list and then split every element of that list on "".
– BoarGules
Dec 27 '18 at 20:27












3 Answers
3






active

oldest

votes


















4














I was able to accomplish the desired transformation with a regular expression:



import re
capitalized = re.sub(
'(^|[-/])s*([A-Za-z])', lambda match: match[0].upper(), phrase)


The expression says "anywhere you match either the start of the string, ^, or a dash or slash followed by maybe some space and a word character, replace the word character with its uppercase."



demo






share|improve this answer























  • 7 seconds ahead of me, nice. Just be wary with using w as it matches any of [a-zA-Z0-9_] (In a second thought it doesn't really matter in this particular case)
    – DeepSpace
    Dec 27 '18 at 20:31












  • Haha I noticed that. Very astute of you, I'll make the tweak
    – wbadart
    Dec 27 '18 at 20:33










  • Wow - just tested and it works. Why do I always make stuff more complicated than it needs to be - ty :)
    – beginAgain
    Dec 27 '18 at 20:35



















2














If you don't want to go with a messy splitting-joining logic, go with a regex:



import re

string = 'test/string - this is a test string'

print(re.sub(r'(^([a-z])|(?<=[-/])s?([a-z]))',
lambda match: match.group(1).upper(), string))
# Test/String - This is a test string





share|improve this answer





























    2














    Using double split



    import re
    ' - '.join([i.strip().capitalize() for i in re.split(' - ','/'.join([i.capitalize() for i in re.split('/',test_phrase)]))])





    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',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      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%2f53950410%2fhow-to-capitalize-specific-letters-in-a-string-given-certain-rules%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      4














      I was able to accomplish the desired transformation with a regular expression:



      import re
      capitalized = re.sub(
      '(^|[-/])s*([A-Za-z])', lambda match: match[0].upper(), phrase)


      The expression says "anywhere you match either the start of the string, ^, or a dash or slash followed by maybe some space and a word character, replace the word character with its uppercase."



      demo






      share|improve this answer























      • 7 seconds ahead of me, nice. Just be wary with using w as it matches any of [a-zA-Z0-9_] (In a second thought it doesn't really matter in this particular case)
        – DeepSpace
        Dec 27 '18 at 20:31












      • Haha I noticed that. Very astute of you, I'll make the tweak
        – wbadart
        Dec 27 '18 at 20:33










      • Wow - just tested and it works. Why do I always make stuff more complicated than it needs to be - ty :)
        – beginAgain
        Dec 27 '18 at 20:35
















      4














      I was able to accomplish the desired transformation with a regular expression:



      import re
      capitalized = re.sub(
      '(^|[-/])s*([A-Za-z])', lambda match: match[0].upper(), phrase)


      The expression says "anywhere you match either the start of the string, ^, or a dash or slash followed by maybe some space and a word character, replace the word character with its uppercase."



      demo






      share|improve this answer























      • 7 seconds ahead of me, nice. Just be wary with using w as it matches any of [a-zA-Z0-9_] (In a second thought it doesn't really matter in this particular case)
        – DeepSpace
        Dec 27 '18 at 20:31












      • Haha I noticed that. Very astute of you, I'll make the tweak
        – wbadart
        Dec 27 '18 at 20:33










      • Wow - just tested and it works. Why do I always make stuff more complicated than it needs to be - ty :)
        – beginAgain
        Dec 27 '18 at 20:35














      4












      4








      4






      I was able to accomplish the desired transformation with a regular expression:



      import re
      capitalized = re.sub(
      '(^|[-/])s*([A-Za-z])', lambda match: match[0].upper(), phrase)


      The expression says "anywhere you match either the start of the string, ^, or a dash or slash followed by maybe some space and a word character, replace the word character with its uppercase."



      demo






      share|improve this answer














      I was able to accomplish the desired transformation with a regular expression:



      import re
      capitalized = re.sub(
      '(^|[-/])s*([A-Za-z])', lambda match: match[0].upper(), phrase)


      The expression says "anywhere you match either the start of the string, ^, or a dash or slash followed by maybe some space and a word character, replace the word character with its uppercase."



      demo







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Dec 27 '18 at 20:34

























      answered Dec 27 '18 at 20:30









      wbadart

      1,7971619




      1,7971619












      • 7 seconds ahead of me, nice. Just be wary with using w as it matches any of [a-zA-Z0-9_] (In a second thought it doesn't really matter in this particular case)
        – DeepSpace
        Dec 27 '18 at 20:31












      • Haha I noticed that. Very astute of you, I'll make the tweak
        – wbadart
        Dec 27 '18 at 20:33










      • Wow - just tested and it works. Why do I always make stuff more complicated than it needs to be - ty :)
        – beginAgain
        Dec 27 '18 at 20:35


















      • 7 seconds ahead of me, nice. Just be wary with using w as it matches any of [a-zA-Z0-9_] (In a second thought it doesn't really matter in this particular case)
        – DeepSpace
        Dec 27 '18 at 20:31












      • Haha I noticed that. Very astute of you, I'll make the tweak
        – wbadart
        Dec 27 '18 at 20:33










      • Wow - just tested and it works. Why do I always make stuff more complicated than it needs to be - ty :)
        – beginAgain
        Dec 27 '18 at 20:35
















      7 seconds ahead of me, nice. Just be wary with using w as it matches any of [a-zA-Z0-9_] (In a second thought it doesn't really matter in this particular case)
      – DeepSpace
      Dec 27 '18 at 20:31






      7 seconds ahead of me, nice. Just be wary with using w as it matches any of [a-zA-Z0-9_] (In a second thought it doesn't really matter in this particular case)
      – DeepSpace
      Dec 27 '18 at 20:31














      Haha I noticed that. Very astute of you, I'll make the tweak
      – wbadart
      Dec 27 '18 at 20:33




      Haha I noticed that. Very astute of you, I'll make the tweak
      – wbadart
      Dec 27 '18 at 20:33












      Wow - just tested and it works. Why do I always make stuff more complicated than it needs to be - ty :)
      – beginAgain
      Dec 27 '18 at 20:35




      Wow - just tested and it works. Why do I always make stuff more complicated than it needs to be - ty :)
      – beginAgain
      Dec 27 '18 at 20:35













      2














      If you don't want to go with a messy splitting-joining logic, go with a regex:



      import re

      string = 'test/string - this is a test string'

      print(re.sub(r'(^([a-z])|(?<=[-/])s?([a-z]))',
      lambda match: match.group(1).upper(), string))
      # Test/String - This is a test string





      share|improve this answer


























        2














        If you don't want to go with a messy splitting-joining logic, go with a regex:



        import re

        string = 'test/string - this is a test string'

        print(re.sub(r'(^([a-z])|(?<=[-/])s?([a-z]))',
        lambda match: match.group(1).upper(), string))
        # Test/String - This is a test string





        share|improve this answer
























          2












          2








          2






          If you don't want to go with a messy splitting-joining logic, go with a regex:



          import re

          string = 'test/string - this is a test string'

          print(re.sub(r'(^([a-z])|(?<=[-/])s?([a-z]))',
          lambda match: match.group(1).upper(), string))
          # Test/String - This is a test string





          share|improve this answer












          If you don't want to go with a messy splitting-joining logic, go with a regex:



          import re

          string = 'test/string - this is a test string'

          print(re.sub(r'(^([a-z])|(?<=[-/])s?([a-z]))',
          lambda match: match.group(1).upper(), string))
          # Test/String - This is a test string






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Dec 27 '18 at 20:30









          DeepSpace

          37.1k44169




          37.1k44169























              2














              Using double split



              import re
              ' - '.join([i.strip().capitalize() for i in re.split(' - ','/'.join([i.capitalize() for i in re.split('/',test_phrase)]))])





              share|improve this answer


























                2














                Using double split



                import re
                ' - '.join([i.strip().capitalize() for i in re.split(' - ','/'.join([i.capitalize() for i in re.split('/',test_phrase)]))])





                share|improve this answer
























                  2












                  2








                  2






                  Using double split



                  import re
                  ' - '.join([i.strip().capitalize() for i in re.split(' - ','/'.join([i.capitalize() for i in re.split('/',test_phrase)]))])





                  share|improve this answer












                  Using double split



                  import re
                  ' - '.join([i.strip().capitalize() for i in re.split(' - ','/'.join([i.capitalize() for i in re.split('/',test_phrase)]))])






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Dec 27 '18 at 20:31









                  mad_

                  3,60211020




                  3,60211020






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53950410%2fhow-to-capitalize-specific-letters-in-a-string-given-certain-rules%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Monofisismo

                      Angular Downloading a file using contenturl with Basic Authentication

                      Olmecas