0
$\begingroup$

I have the following list

l = {{"CENTRALE-DETACHES", 485., 20.}, {"AGEN", 132., 
  5.}, {"AIX EN PROVENCE", 1200., 26.}, {"AMIENS", 400., 
  11.}, {"ANGERS", 262., 7.}, {"BASSE TERRE", 136., 5.}, {"BASTIA", 
  104., 5.}, {"BESANCON", 228., 7.}, {"BORDEAUX", 458., 
  11.}, {"BOURGES", 142., 5.}, {"CAEN", 282., 8.}, {"CAYENNE", 78., 
  3.}, {"CHAMBERY", 238., 7.}, {"COLMAR", 448., 12.}, {"DIJON", 242., 
  7.}, {"DOUAI", 914., 21.}, {"FORT DE France", 106., 
  5.}, {"GRENOBLE", 334., 9.}, {"LIMOGES", 164., 6.}, {"LYON", 608., 
  15.}, {"METZ", 276., 7.}, {"MONTPELLIER", 470., 11.}, {"NANCY", 
  308., 8.}, {"NIMES", 362., 10.}, {"ORLEANS", 258., 7.}, {"PARIS", 
  2822., 58.}, {"PAU", 268., 7.}, {"POITIERS", 328., 8.}, {"REIMS", 
  252., 7.}, {"RENNES", 738., 17.}, {"RIOM", 260., 7.}, {"ROUEN", 
  358., 10.}, {"SAINT DENIS DE LA REUNION", 200., 6.}, {"TOULOUSE", 
  384., 10.}, {"VERSAILLES", 944., 21.}, {"COM-NOUVELLE-CALEDONIE", 
  160., 6.}}

I would like to know if there is a programatic way to change the string to lower case, the firs letter of each name being capitalized that is RIOM -> Riom, SAINT DENIS DE LA REUNION -> Saint Denis de la Reunion, COM-NOUVELLE-CALEDONIE -> COM-Nouvelle-Caledonie.

$\endgroup$
7

1 Answer 1

2
$\begingroup$

Riffing off of J.M.'s nice comment, and assuming there are some words that should be entirely lowercase and some that are entirely uppercase.

canonUpperWord[s_] := 
 StringReplace[
  ToLowerCase[
   s], {WordBoundary ~~ x : LetterCharacter :> ToUpperCase[x]}]

allLower = canonUpperWord /@ {"en", "de", "la", "et"};
allUpper = canonUpperWord /@ {"COM", "DROM", "TOM"};

l /. s_String :> 
  StringReplace[canonUpperWord@s, 
   Join[WordBoundary ~~ # ~~ WordBoundary -> ToLowerCase[#] & /@ 
     allLower, 
    WordBoundary ~~ # ~~ WordBoundary -> ToUpperCase[#] & /@ 
     allUpper]]

If you want more fine grained control over splitting of words than WordBoundary, it's possible to of course cook up something yourself using StringSplit and StringJoin:

capFirstWord[s_String] := 
 StringJoin[ToUpperCase[First[#]], Rest[#]] &[
  StringSplit[ToLowerCase[s], ""]]

capTheString[s_String] := 
 StringReplace[s, 
  Map[# -> capFirstWord[#] &, StringSplit[s, {" ", "-", "'"}]]]

altCanonUpper[s_] := capTheString[s]
$\endgroup$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.