Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format raw string with different expressions inside?

Let's say, we want to catch something with regex, using rawstring to define the pattern, which pattern has repeating elements, and variables inside. And we also want to use the format() string formatting form. How to do this?

import re text = '"""!some text' re.findall(r'"{3}{symbol}some\stext'.format(symbol='!'), text) 

But this line leads us to an IndexError:

# IndexError: tuple index out of range 

So, my question is: how to format a raw string if it has formatting curly-braces expression, and repeating curly-braces expression inside?

Thanks in advance!

like image 607
Peter Varo Avatar asked May 25 '13 22:05

Peter Varo


People also ask

Can you format a raw string Python?

In Python string format, a raw string ignores all types of formatting within a string including the escape characters. As you can see in the output, by constructing a raw string you can retain quotes, backslashes that are used to escape and other characters, as in.

Can a triple quoted string be f string formatted?

Inside this string, you can write a Python expression between { } characters that can refer to variables or literal values. f-strings use the same rules as normal strings, raw strings, and triple quoted strings.

What is a string formatting expression?

String formatting is also known as String interpolation. It is the process of inserting a custom string or variable in predefined text. custom_string = "String formatting" print(f"{custom_string} is a powerful technique") Powered by Datacamp Workspace. String formatting is a powerful technique.


1 Answers

Use f-strings (introduced in Python 3.6):

a = 15 print(fr'Escape is here:\n but still {a}')  # => Escape is here:\n but still 15 
like image 167
Daniel Malachov Avatar answered Sep 20 '22 17:09

Daniel Malachov