Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic string formatting using string.format and List<T>.Count()

I have to print out some PDFs for a project at work. Is there way to provide dynamic padding, IE. not using a code hard-coded in the format string. But instead based on the count of a List.

Ex.

If my list is 1000 elements long, I want to have this:

Part_0001_Filename.pdf... Part_1000_Filename.pdf

And if my list is say 500 elements long, I want to have this formatting:

Part_001_Filename.pdf... Part_500_Filename.PDF

The reason for this is how Windows orders file names. It sorts them alphabetically left-to-right or right-to-left, So I must use the leading zero, otherwise the ordering in the folder is messed up.

like image 500
Chris Avatar asked Jun 07 '09 23:06

Chris


People also ask

How do you set a string to dynamic value in Python?

With the release of Python 3.6, we were introduced to F-strings. As their name suggests, F-strings begin with "f" followed by a string literal. We can insert values dynamically into our strings with an identifier wrapped in curly braces, just like we did in the format() method.

What is %s in string format?

The %s operator is put where the string is to be specified. The number of values you want to append to a string should be equivalent to the number specified in parentheses after the % operator at the end of the string value. The following Python code illustrates the way of performing string formatting.

Why do we use formatting string?

format gives you more power in "formatting" the string; and concatenation means you don't have to worry about accidentally putting in an extra %s or missing one out. String. format is also shorter. Which one is more readable depends on how your head works.


1 Answers

The simplest way is probably to build the format string dynamically too:

static List<string> FormatFileNames(List<string> files)
{
    int width = (files.Count+1).ToString("d").Length;

    string formatString = "Part_{0:D" + width + "}_{1}.pdf";

    List<string> result = new List<string>();

    for (int i=0; i < files.Count; i++)
    {
        result.Add(string.Format(formatString, i+1, files[i]));
    }
    return result;
}

This could be done slightly more simply with LINQ if you like:

static List<string> FormatFileNames(List<string> files)
{
    int width = (files.Count+1).ToString("d").Length;        
    string formatString = "Part_{0:D" + width + "}_{1}.pdf";

    return files.Select((file, index) => 
                            string.Format(formatString, index+1, file))
                .ToList();
}
like image 157
Jon Skeet Avatar answered Sep 23 '22 01:09

Jon Skeet