Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping single quote in String.Format()

I have been all over the 'tubes and I can't figure this one out. Might be simple.

The following String.Format call:

return dt.ToString("MMM d yy 'at' H:mmm"); 

Correctly returns this:

Sep 23 08 at 12:57

Now let's say I want to add a single quote before the year, to return this:

Sep 23 '08 at 12:57

Since the single quote is a reserved escape character, how do I escape the single quote to get it to display?

I have tried double, triple, and quad single quotes, with no luck.

like image 892
Jeff Atwood Avatar asked Aug 29 '09 10:08

Jeff Atwood


People also ask

How do you escape quotation marks in a string?

You can put a backslash character followed by a quote ( \" or \' ). This is called an escape sequence and Python will remove the backslash, and put just the quote in the string. Here is an example. The backslashes protect the quotes, but are not printed.

How do you escape a single quote from a single quote?

' End first quotation which uses single quotes. " Start second quotation, using double-quotes. ' Quoted character. " End second quotation, using double-quotes.

How do you escape a string format?

String's format() method uses percent sign( % ) as prefix of format specifier. For example: To use number in String's format() method, we use %d , but what if you actually want to use percent sign in the String. If you want to escape percent sign in String's format method, you can use % twice ( %% ).


1 Answers

You can escape it using a backslash which you will have to escape. Either

return dt.ToString(@"MMM d \'yy 'at' H:mmm"); 

or

return dt.ToString("MMM d \\'yy 'at' H:mmm"); 
like image 108
Martin Liversage Avatar answered Sep 22 '22 02:09

Martin Liversage