Formats a string without requiring all values to be present.

  This function allows substitutions to be gradually made in several steps
  rather than all at once.  Similar to string.Template.safe_substitute.
778957
def partial_format(target, **kwargs):
  
  output = target[:]

  for tag, var in re.findall(r'(\{(.*?)\})', output):
    root = var.split('.')[0]  # dot notation
    root = root.split('[')[0]  # dict notation
    if root in kwargs:
      output = output.replace(tag, tag.format(**{root: kwargs[root]}))

  return output
58557
function format(value) {
    if (typeof value == 'number')
      return value;

    var str = String(value);
    var ary = str.split('\n').map((e) => JSON.stringify(e));
    if (ary.length > 1) {
      // If the string has newlines, start it off on its own line so that
      // it's easier to compare against another string with newlines.
      return '\n' + ary.join('\n');
    } else {
      return ary.join('\n');
    }
  }
914147
function format(str, ctx) {
	var splitter = '{',
		isInside = false,
		segment,
		valueAndFormat,
		path,
		i,
		len,
		ret = [],
		val,
		index;
	
	while ((index = str.indexOf(splitter)) !== -1) {
		
		segment = str.slice(0, index);
		if (isInside) { // we're on the closing bracket looking back
			
			valueAndFormat = segment.split(':');
			path = valueAndFormat.shift().split('.'); // get first and leave format
			len = path.length;
			val = ctx;

			// Assign deeper paths
			for (i = 0; i < len; i++) {
				val = val[path[i]];
			}

			// Format the replacement
			if (valueAndFormat.length) {
				val = formatSingle(valueAndFormat.join(':'), val);
			}

			// Push the result and advance the cursor
			ret.push(val);
			
		} else {
			ret.push(segment);
			
		}
		str = str.slice(index + 1); // the rest
		isInside = !isInside; // toggle
		splitter = isInside ? '}' : '{'; // now look for next matching bracket
	}
	ret.push(str);
	return ret.join('');
}
1140477
function template(str, params){
  return str.replace(/%(\w*)%/g, function(m, key){
    return params[key];
  });
}
282753
public String cleanupPreFormatted(String value) {
        String result = value;
        if (value != null) {
            Matcher matcher = PRE_FORMATTED_PATTERN.matcher(value);
            if (matcher.matches()) {
                String escapedBody = matcher.group(1);
                result = StringEscapeUtils.unescapeHtml4(escapedBody);
            }
        }
        return result;
    }
599062
function format (str, tokens) {
  for (let i = 0; i < tokens.length; i++) {
    str = str.replace(tokens[i].token, tokens[i].replacement)
  }
  return str
}
986061
static String format(String template, Object... args) {
        template = String.valueOf(template); // null -> "null"

        if (N.isNullOrEmpty(args)) {
            return template;
        }

        // start substituting the arguments into the '%s' placeholders
        final StringBuilder sb = Objectory.createStringBuilder(template.length() + 16 * args.length);
        int templateStart = 0;
        int i = 0;

        String placeholder = "{}";
        int placeholderStart = template.indexOf(placeholder);

        if (placeholderStart < 0) {
            placeholder = "%s";
            placeholderStart = template.indexOf(placeholder);
        }

        while (placeholderStart >= 0 && i < args.length) {
            sb.append(template, templateStart, placeholderStart);
            sb.append(N.toString(args[i++]));
            templateStart = placeholderStart + 2;
            placeholderStart = template.indexOf(placeholder, templateStart);
        }

        sb.append(template, templateStart, template.length());

        // if we run out of placeholders, append the extra args in square braces
        if (i < args.length) {
            sb.append(" [");
            sb.append(N.toString(args[i++]));
            while (i < args.length) {
                sb.append(", ");
                sb.append(N.toString(args[i++]));
            }
            sb.append(']');
        }

        final String result = sb.toString();

        Objectory.recycle(sb);

        return result;
    }
1228738
public static String format(String formatString, Object... args) {
    // Rewrites the varargs so that objects that need special formatting are
    // replaced with formatted strings, then hands off to {@link String#format}.

    Object[] formattedArgs = new Object[args.length];
    for (int i = 0; i < args.length; ++i) {
      formattedArgs[i] = formatObject(args[i]);
    }

    return String.format(formatString, (Object[]) formattedArgs);
  }
65893
def format_string(string_to_format, wordstyle="lowercase", separator=" "):
    
    # first split the string up into its constituent words
    words = string_to_format.split(" ")

    # format the individual words
    function_map = {
        "lowercase": format_word_list_lowercase,
        "uppercase": format_word_list_uppercase,
        "capitalize": format_word_list_capitalize,
        "mixedcase": format_word_list_mixedcase
    }

    try:
        words = function_map[wordstyle](words)
    except KeyError:
        msg = "Passed in an invalid wordstyle, allowed styles are {}"
        raise InvalidWordStyleError(msg.format(function_map.keys()))

    # now add in the separator and return
    return str(separator).join(words)
377575
def format(
        self,
        format_string,
        module=None,
        param_dict=None,
        force_composite=False,
        attr_getter=None,
    ):
        
        # fix python 2 unicode issues
        if python2 and isinstance(format_string, str):
            format_string = format_string.decode("utf-8")

        if param_dict is None:
            param_dict = {}

        # if the processed format string is not in the cache then create it.
        if format_string not in self.block_cache:
            self.build_block(format_string)

        first_block = self.block_cache[format_string]

        def get_parameter(key):
            """
            function that finds and returns the value for a placeholder.
            """
            if key in param_dict:
                # was a supplied parameter
                param = param_dict.get(key)
            elif module and hasattr(module, key):
                param = getattr(module, key)
                if hasattr(param, "__call__"):
                    # we don't allow module methods
                    raise Exception()
            elif attr_getter:
                # get value from attr_getter function
                try:
                    param = attr_getter(key)
                except:  # noqa e722
                    raise Exception()
            else:
                raise Exception()
            if isinstance(param, Composite):
                if param.text():
                    param = param.copy()
                else:
                    param = u""
            elif python2 and isinstance(param, str):
                param = param.decode("utf-8")
            return param

        # render our processed format
        valid, output = first_block.render(get_parameter, module)

        # clean things up a little
        if isinstance(output, list):
            output = Composite(output)
        if not output:
            if force_composite:
                output = Composite()
            else:
                output = ""

        return output
777931
def pretty_str(self, indent=0):
        
        indent = ' ' * indent
        values = '{{{}}}'.format(', '.join(map(pretty_str, self.value)))

        if self.parenthesis:
            return '{}({})'.format(indent, values)
        return '{}{}'.format(indent, values)
1087273
function interpolate(string) {
        // Replaces all occurrences of `#` with a unique number and template tokens with content.
        return _.template(string.replace(/\#/g, /\d+/.exec(templateData.uid)))(templateData);
      }
368
def preprocess(string):
    
    string = unicode(string, encoding="utf-8")
    # convert diacritics to simpler forms
    string = regex1.sub(lambda x: accents[x.group()], string)
    # remove all rest of the unwanted characters
    return regex2.sub('', string).encode('utf-8')
821714
private static String formatParameterValueAsUnescapedVariableTemplate(final Object parameterValue) {
        // Get the value
        if (parameterValue == null) { // If null (= NO_VALUE), empty String
            return "";
        }
        // If it is not multivalued (e.g. non-List) simply escape and return
        if (!(parameterValue instanceof List<?>)) {
            return parameterValue.toString();
        }
        // It is multivalued, so iterate and escape each item (no need to escape the comma separating them, it's an allowed char)
        final List<?> values = (List<?>)parameterValue;
        final int valuesLen = values.size();
        final StringBuilder strBuilder = new StringBuilder(valuesLen * 16);
        for (int i = 0; i < valuesLen; i++) {
            final Object valueItem = values.get(i);
            if (strBuilder.length() > 0) {
                strBuilder.append(',');
            }
            strBuilder.append(valueItem == null? "" : valueItem.toString());
        }
        return strBuilder.toString();
    }
956524
def safe_print(ustring, errors='replace', **kwargs):
    
    encoding = sys.stdout.encoding or 'utf-8'
    if sys.version_info[0] == 3:
        print(ustring, **kwargs)
    else:
        bytestr = ustring.encode(encoding, errors=errors)
        print(bytestr, **kwargs)
1069551
def format(self, template=None):
        
        pattern = r"(?:<([^<]*?)\$(\w+)([^>]*?)>)"
        s = sub(pattern, self._format_repl, template or self.template)
        s = self._str_fix_whitespace(s)
        return s
1097646
function format(string) {
  string = _.toString(string);

  // Replace all code snippets with a token.
  var snippets = [];
  string = string.replace(reCode, function(match) {
    snippets.push(match);
    return token;
  });

  return string
    // Add line breaks.
    .replace(/:\n(?=[\t ]*\S)/g, ':<br>\n')
    .replace(/\n( *)[-*](?=[\t ]+\S)/g, '\n<br>\n$1*')
    .replace(/^[\t ]*\n/gm, '<br>\n<br>\n')
    // Normalize whitespace.
    .replace(/\n +/g, ' ')
    // Italicize parentheses.
    .replace(/(^|\s)(\(.+\))/g, '$1*$2*')
    // Mark numbers as inline code.
    .replace(/[\t ](-?\d+(?:.\d+)?)(?!\.[^\n])/g, ' `$1`')
    // Replace all tokens with code snippets.
    .replace(reToken, function(match) {
      return snippets.shift();
    })
    .trim();
}