Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Python's triple-quote string work?

Tags:

python

string

How should this function be changed to return "123456"?

def f():     s = """123     456"""     return s 

UPDATE: Everyone, the question is about understanding how to not have \t or whatever when having a multiline comment, not how to use the re module.

like image 424
Ram Rachum Avatar asked Oct 05 '09 14:10

Ram Rachum


People also ask

How do you add triple quotes to a string in Python?

Create a string in Python (single, double, triple quotes, str()) In Python, a string ( str ) is created by enclosing text in single quotes ' , double quotes " , and triple quotes ( ''' , """ ). It is also possible to convert objects of other types to strings with str() .

What does three apostrophes mean in Python?

Three apostrophes (or speech marks) make your string a triple-quoted string. This allows it to span multiple lines.

What does 3 quotation marks mean?

The triple quotation is a nice way to be able to include other types of quotation within your string without having to use escape characters. For example: print("He said \"my name's John\"") That example requires escape characters \" to use double quote marks.


2 Answers

Don't use a triple-quoted string when you don't want extra whitespace, tabs and newlines.

Use implicit continuation, it's more elegant:

def f():     s = ('123'          '456')     return s 
like image 51
nosklo Avatar answered Sep 26 '22 09:09

nosklo


def f():   s = """123\ 456"""   return s 

Don't indent any of the blockquote lines after the first line; end every line except the last with a backslash.

like image 38
Slumberheart Avatar answered Sep 23 '22 09:09

Slumberheart