Unmatched python ошибка

I'm trying to use f-strings in python to substitute some variables into a string that I'm printing, and I'm getting a syntax error. Here's my code: print(f"{index+1}. {value[-1].replace("...

I’m trying to use f-strings in python to substitute some variables into a string that I’m printing, and I’m getting a syntax error.
Here’s my code:

print(f"{index+1}. {value[-1].replace("[Gmail]/", '')}")

I only started having the problem after I added the replace. I’ve checked plenty of times and I’m certain that I’m not missing a parenthesis. I know that there are plenty of other ways to accomplish this, some of which are probably better, but I’m curious why this doesn’t work.

smci's user avatar

smci

31.5k18 gold badges112 silver badges146 bronze badges

asked May 14, 2021 at 20:07

Cameron Delong's user avatar

Cameron DelongCameron Delong

3751 gold badge3 silver badges11 bronze badges

3

Your problem is double quotes inside double quotes.
For example,

  • OK —> f"hello ' this is good"
  • OK —> f'hello " this is good'
  • ERROR —> f"hello " this breaks"
  • ERROR —> f'hello ' this breaks'

This one should work correctly:

print(f"{index+1}. {value[-1].replace('[Gmail]/', '')}")

Out of scope but still I do not advise you to use replace inside f-string. I think that it would be better to move it to a temp variable.

Seymour's user avatar

Seymour

2,9762 gold badges21 silver badges45 bronze badges

answered May 14, 2021 at 20:11

Oleksandr Dashkov's user avatar

I had the same issue,change all the double quote within the parenthesis to single quotes.It should work
eg from
print( f» Water : {resources[«water»] } » )
to
print( f» Water : {resources[‘water’] } » )

answered Mar 28, 2022 at 10:16

user17597998's user avatar

1

Seems like this does not work

x = 'hellothere'
print(f"replace {x.replace("hello",'')}")

error

    print(f"replace {x.replace("hello",'')}")
                                ^
SyntaxError: f-string: unmatched '('

Try this instead

x = 'hellothere'
print(f"replace {x.replace('hello','')}")

single quotes 'hello'
output is

replace there

answered May 14, 2021 at 20:11

Thavas Antonio's user avatar

Thavas AntonioThavas Antonio

5,7371 gold badge14 silver badges40 bronze badges

Another way to do some string formatting (which in my opinion improves readability) :

print("{0}. {1}".format(index+1, 
                        value[-1].replace("[Gmail]/", "")))

answered May 14, 2021 at 20:11

Charles Dupont's user avatar

To fix the SyntaxError: f-string: unmatched ‘(‘ in Python, you need to pay attention to use single or double quotes in f-string. You can change it or not use it. Please read the following article for details. 

New built-in string formatting method from Python 3.6 in the following syntax:

f''a{value:pattern}b''

Parameters:

  • f character: use the string f to format the string.
  • a,b: characters to format.
  • {value:pattern}: string elements need to be formatted.
  • pattern: string format.

In simple terms, we format a string in Python by writing the letter f or F in front of the string and then assigning a replacement value to the replacement field. We then transform the replacement value assigned to match the format in the replace field and complete the process.

The SyntaxError: f-string: unmatched ‘(‘ in Python happens because you use unreasonable single or double quotes in f-string.

Example: 

testStr = 'visit learnshareit website'

# Put variable name with the string in double quotes in f-string for formatting
newStr = f"{(testStr + "hello")}"
print(newStr)

Output:

  File "code.py", line 4
    newStr = f"{(testStr + "hello")}"
                            ^
SyntaxError: invalid syntax

How to solve this error?

Change the quotes

The simplest way is to change the quotes. If your f-string contains double quotes, put the string inside it with single quotes.

Example:

testStr = 'visit learnshareit website'

# Use single quotes for strings in f-string when f-string contains double quotes
newStr = f"{(testStr + ' hello')}"
print(newStr)

Output:

visit learnshareit website hello

Similarly, we will do the opposite if the f-string carries single quotes. The string in it must carry double quotes.

Example:

testStr = 'visit learnshareit website'

# f-string contains single quotes. The string must contain double quotes
newStr = f'{(testStr + " hello")}'
print(newStr)

Output:

visit learnshareit website hello

Do not use single or double quotes

If the problem is with quotes confusing you, limit their use inside the f-string.

Example:

  • I want to concatenate two strings instead of using quotes inside the f-string. Then I declare 2 variables containing two strings and use the addition operator to concatenate two strings inside f-string so that will avoid SyntaxError: f- string: unmatched ‘(‘.
testStr = 'visit learnshareit website'
secondStr = '!!!'

newStr = f'{ testStr + secondStr }'
print(newStr)

Output:

visit learnshareit website!!!

Summary

The SyntaxError: f-string: unmatched ‘(‘ in Python has been resolved. You can use one of two methods above for this problem. If there are better ways, please leave a comment. We appreciate this. Thank you for reading!

Maybe you are interested:

  • How To Resolve SyntaxError: ‘Break’ Outside Loop In Python
  • How To Resolve SyntaxError: f-string: Empty Expression Not Allowed In Python
  • How To Resolve SyntaxError: F-string Expression Part Cannot Include A Backslash In Python

Jason Wilson

My name is Jason Wilson, you can call me Jason. My major is information technology, and I am proficient in C++, Python, and Java. I hope my writings are useful to you while you study programming languages.


Name of the university: HHAU
Major: IT
Programming Languages: C++, Python, Java

I’m trying to use f-strings in python to substitute some variables into a string that I’m printing, and I’m getting a syntax error.
Here’s my code:

print(f"{index+1}. {value[-1].replace("[Gmail]/", '')}")

I only started having the problem after I added the replace. I’ve checked plenty of times and I’m certain that I’m not missing a parenthesis. I know that there are plenty of other ways to accomplish this, some of which are probably better, but I’m curious why this doesn’t work.

smci's user avatar

smci

31.5k18 gold badges112 silver badges146 bronze badges

asked May 14, 2021 at 20:07

Cameron Delong's user avatar

Cameron DelongCameron Delong

3751 gold badge3 silver badges11 bronze badges

3

Your problem is double quotes inside double quotes.
For example,

  • OK —> f"hello ' this is good"
  • OK —> f'hello " this is good'
  • ERROR —> f"hello " this breaks"
  • ERROR —> f'hello ' this breaks'

This one should work correctly:

print(f"{index+1}. {value[-1].replace('[Gmail]/', '')}")

Out of scope but still I do not advise you to use replace inside f-string. I think that it would be better to move it to a temp variable.

Seymour's user avatar

Seymour

2,9762 gold badges21 silver badges45 bronze badges

answered May 14, 2021 at 20:11

Oleksandr Dashkov's user avatar

I had the same issue,change all the double quote within the parenthesis to single quotes.It should work
eg from
print( f» Water : {resources[«water»] } » )
to
print( f» Water : {resources[‘water’] } » )

answered Mar 28, 2022 at 10:16

user17597998's user avatar

1

Seems like this does not work

x = 'hellothere'
print(f"replace {x.replace("hello",'')}")

error

    print(f"replace {x.replace("hello",'')}")
                                ^
SyntaxError: f-string: unmatched '('

Try this instead

x = 'hellothere'
print(f"replace {x.replace('hello','')}")

single quotes 'hello'
output is

replace there

answered May 14, 2021 at 20:11

Thavas Antonio's user avatar

Thavas AntonioThavas Antonio

5,7371 gold badge14 silver badges40 bronze badges

Another way to do some string formatting (which in my opinion improves readability) :

print("{0}. {1}".format(index+1, 
                        value[-1].replace("[Gmail]/", "")))

answered May 14, 2021 at 20:11

Charles Dupont's user avatar

Created on 2021-09-02 14:55 by Greg Kuhn, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (9)
msg400920 — (view) Author: Greg Kuhn (Greg Kuhn) Date: 2021-09-02 14:55
Hi All, 
Is the below a bug? Shouldn't the interpreter be complaining about a curly brace?

$ python
Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) [MSC v.1926 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> num = 10
>>> f'[{num]'
  File "<stdin>", line 1
SyntaxError: f-string: unmatched ']'
>>>
msg400925 — (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2021-09-02 15:29
I think the error is short for "I found a ']' without a matching '['".
msg400930 — (view) Author: Greg Kuhn (Greg Kuhn) Date: 2021-09-02 15:45
But doesn't the square bracket have no relevance here?
It's not within a curly bracketed string so shouldn't be treated specially.

I would have expected the error to be: SyntaxError: f-string: unmatched '}'.

Unless I need to go back and reread pep498...
msg400942 — (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2021-09-02 17:17
I think it's basically this error:

>>> num]
  File "<stdin>", line 1
    num]
       ^
SyntaxError: unmatched ']'

Although I'd have to look at it more to see why that's the error it chose to display, instead of the curly brace.
msg401029 — (view) Author: Terry J. Reedy (terry.reedy) * (Python committer) Date: 2021-09-04 02:06
The behavior remains the same in 3.11 ('main' branch).  New PEG parser parses this the same.

(Pablo, if there is a mistake below, please correct.)

Normally, the parser copies code chars between quotes, with or without '' interpretation, into a string object.  When the 'f' prefix is given, the string gets divided into substrings and replacement fields.  The code part of each replacement field is separately parsed.  There are two options: 1. parse the field code while looking for an endcode marker; 2. look ahead for an endcode marker and then parse the code.

The current behavior is consistent with opotion 1 and the python policy of reporting the first error found and exiting, rather than trying to resynchronize to try to find more errors.
msg401034 — (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2021-09-04 02:58
I don't think it really makes a difference, but here's some background:

For f-strings, the parser itself does not break apart the f-string into (<text>, <expression>) parts. There's a custom parser (at https://github.com/python/cpython/blob/0b58e863df9970b290a4de90c67f9ac30c443817/Parser/string_parser.c#L837) which does that. Then the normal parser is used to parse the expression portion.

I think the error shown here is not in the expression parser, but in the fstring parser in fstring_find_expr(), at https://github.com/python/cpython/blob/0b58e863df9970b290a4de90c67f9ac30c443817/Parser/string_parser.c#L665

As Terry says, it's not incorrect to print the error show in this bug report.

To further diverge:

There's been talk about using the normal parser to pull apart the entire f-string, instead of using the two-pass version I mention above. But we've never gotten past just talking about it. There are pros and cons for doing it with the normal parser, but that's a discussion for a different forum.
msg401042 — (view) Author: Pablo Galindo Salgado (pablogsal) * (Python committer) Date: 2021-09-04 12:29
> But we've never gotten past just talking about it

Stay tuned! :)

 https://github.com/we-like-parsers/cpython/tree/fstring-grammar
msg401046 — (view) Author: Terry J. Reedy (terry.reedy) * (Python committer) Date: 2021-09-04 16:38
Thank you Eric.  I can see now that the actual process is a somewhat complicated mix of the simple options 1 and 2 I imagined above.  It is like option 2, except that everything between '{' and '}' is partially parsed enough to create a format object.  This is required to ignore quoted braces

>>> f'{"}"'
SyntaxError: f-string: expecting '}'

and detect valid '!' and ':' markers.  In that partial parsing, unmatched fences are detected and reported, while other syntax errors are not.  If my option 1 above were true, the first example below would instead report the 'a a' error.

>>> f'{a a'
SyntaxError: f-string: expecting '}'
>>> f'{a a]'
SyntaxError: f-string: unmatched ']'
>>> f'{a a}'
SyntaxError: f-string: invalid syntax. Perhaps you forgot a comma?

The second plausibly could, but outside of the f-string context, the error is the same.
>>> a a]
SyntaxError: unmatched ']'
 
Greg, the fuller answer to your question is that the interpreter is only *required* to report that there is an error and some indication of where.  "SyntaxError: invalid syntax" is the default.  It may have once been all that was ever reported.

A lot of recent effort has gone into adding detail into what is wrong and what the fix might be.  But both additions sometimes involve choices that may not meet a particular person's expectation.  Another person, expecting linear rather than nested parsing, might look at the first example above and ask whether the interpreter should be complaining about the 'a a' syntax error instead of the following lack of '}' f-string error.  And I would not call it a bug if it were to do so in the future.
msg401048 — (view) Author: Greg Kuhn (Greg Kuhn) Date: 2021-09-04 17:35
I see, thank you all for the detailed investigation and explanation!!

Agreed Terry, anyone who reads the error should be able to parse it themselves and see what the errors is. Pointing the user to the error site is the most important piece.
History
Date User Action Args
2022-04-11 14:59:49 admin set github: 89249
2021-09-04 17:35:20 Greg Kuhn set messages:
+ msg401048
2021-09-04 16:38:49 terry.reedy set messages:
+ msg401046
2021-09-04 12:29:38 pablogsal set messages:
+ msg401042
2021-09-04 02:58:34 eric.smith set messages:
+ msg401034
2021-09-04 02:07:00 terry.reedy set status: open -> closed

versions:
+ Python 3.9, Python 3.10, Python 3.11
nosy:
+ pablogsal, terry.reedy

messages:
+ msg401029
resolution: not a bug
stage: resolved

2021-09-02 17:17:34 eric.smith set messages:
+ msg400942
2021-09-02 15:45:59 Greg Kuhn set messages:
+ msg400930
2021-09-02 15:29:06 eric.smith set nosy:
+ eric.smith
messages:
+ msg400925
2021-09-02 14:55:20 Greg Kuhn create

Обработка ошибок увеличивает отказоустойчивость кода, защищая его от потенциальных сбоев, которые могут привести к преждевременному завершению работы.

Синтаксис обработки исключений

Прежде чем переходить к обсуждению того, почему обработка исключений так важна, и рассматривать встроенные в Python исключения, важно понять, что есть тонкая грань между понятиями ошибки и исключения.

Ошибку нельзя обработать, а исключения Python обрабатываются при выполнении программы. Ошибка может быть синтаксической, но существует и много видов исключений, которые возникают при выполнении и не останавливают программу сразу же. Ошибка может указывать на критические проблемы, которые приложение и не должно перехватывать, а исключения — состояния, которые стоит попробовать перехватить. Ошибки — вид непроверяемых и невозвратимых ошибок, таких как OutOfMemoryError, которые не стоит пытаться обработать.

Обработка исключений делает код более отказоустойчивым и помогает предотвращать потенциальные проблемы, которые могут привести к преждевременной остановке выполнения. Представьте код, который готов к развертыванию, но все равно прекращает работу из-за исключения. Клиент такой не примет, поэтому стоит заранее обработать конкретные исключения, чтобы избежать неразберихи.

Ошибки могут быть разных видов:

  • Синтаксические
  • Недостаточно памяти
  • Ошибки рекурсии
  • Исключения

Разберем их по очереди.

Синтаксические ошибки (SyntaxError)

Синтаксические ошибки часто называют ошибками разбора. Они возникают, когда интерпретатор обнаруживает синтаксическую проблему в коде.

Рассмотрим на примере.

a = 8
b = 10
c = a b
File "", line 3
 c = a b
       ^
SyntaxError: invalid syntax

Стрелка вверху указывает на место, где интерпретатор получил ошибку при попытке исполнения. Знак перед стрелкой указывает на причину проблемы. Для устранения таких фундаментальных ошибок Python будет делать большую часть работы за программиста, выводя название файла и номер строки, где была обнаружена ошибка.

Недостаточно памяти (OutofMemoryError)

Ошибки памяти чаще всего связаны с оперативной памятью компьютера и относятся к структуре данных под названием “Куча” (heap). Если есть крупные объекты (или) ссылки на подобные, то с большой долей вероятности возникнет ошибка OutofMemory. Она может появиться по нескольким причинам:

  • Использование 32-битной архитектуры Python (максимальный объем выделенной памяти невысокий, между 2 и 4 ГБ);
  • Загрузка файла большого размера;
  • Запуск модели машинного обучения/глубокого обучения и много другое;

Обработать ошибку памяти можно с помощью обработки исключений — резервного исключения. Оно используется, когда у интерпретатора заканчивается память и он должен немедленно остановить текущее исполнение. В редких случаях Python вызывает OutofMemoryError, позволяя скрипту каким-то образом перехватить самого себя, остановить ошибку памяти и восстановиться.

Но поскольку Python использует архитектуру управления памятью из языка C (функция malloc()), не факт, что все процессы восстановятся — в некоторых случаях MemoryError приведет к остановке. Следовательно, обрабатывать такие ошибки не рекомендуется, и это не считается хорошей практикой.

Ошибка рекурсии (RecursionError)

Эта ошибка связана со стеком и происходит при вызове функций. Как и предполагает название, ошибка рекурсии возникает, когда внутри друг друга исполняется много методов (один из которых — с бесконечной рекурсией), но это ограничено размером стека.

Все локальные переменные и методы размещаются в стеке. Для каждого вызова метода создается стековый кадр (фрейм), внутрь которого помещаются данные переменной или результат вызова метода. Когда исполнение метода завершается, его элемент удаляется.

Чтобы воспроизвести эту ошибку, определим функцию recursion, которая будет рекурсивной — вызывать сама себя в бесконечном цикле. В результате появится ошибка StackOverflow или ошибка рекурсии, потому что стековый кадр будет заполняться данными метода из каждого вызова, но они не будут освобождаться.

def recursion():
    return recursion()

recursion()
---------------------------------------------------------------------------

RecursionError                            Traceback (most recent call last)

 in 
----> 1 recursion()


 in recursion()
      1 def recursion():
----> 2     return recursion()


... last 1 frames repeated, from the frame below ...


 in recursion()
      1 def recursion():
----> 2     return recursion()


RecursionError: maximum recursion depth exceeded

Ошибка отступа (IndentationError)

Эта ошибка похожа по духу на синтаксическую и является ее подвидом. Тем не менее она возникает только в случае проблем с отступами.

Пример:

for i in range(10):
    print('Привет Мир!')
  File "", line 2
    print('Привет Мир!')
        ^
IndentationError: expected an indented block

Исключения

Даже если синтаксис в инструкции или само выражение верны, они все равно могут вызывать ошибки при исполнении. Исключения Python — это ошибки, обнаруживаемые при исполнении, но не являющиеся критическими. Скоро вы узнаете, как справляться с ними в программах Python. Объект исключения создается при вызове исключения Python. Если скрипт не обрабатывает исключение явно, программа будет остановлена принудительно.

Программы обычно не обрабатывают исключения, что приводит к подобным сообщениям об ошибке:

Ошибка типа (TypeError)

a = 2
b = 'PythonRu'
a + b
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

 in 
      1 a = 2
      2 b = 'PythonRu'
----> 3 a + b


TypeError: unsupported operand type(s) for +: 'int' and 'str'

Ошибка деления на ноль (ZeroDivisionError)

10 / 0
---------------------------------------------------------------------------

ZeroDivisionError                         Traceback (most recent call last)

 in 
----> 1 10 / 0


ZeroDivisionError: division by zero

Есть разные типы исключений в Python и их тип выводится в сообщении: вверху примеры TypeError и ZeroDivisionError. Обе строки в сообщениях об ошибке представляют собой имена встроенных исключений Python.

Оставшаяся часть строки с ошибкой предлагает подробности о причине ошибки на основе ее типа.

Теперь рассмотрим встроенные исключения Python.

Встроенные исключения

BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StopAsyncIteration
      +-- ArithmeticError
      |    +-- FloatingPointError
      |    +-- OverflowError
      |    +-- ZeroDivisionError
      +-- AssertionError
      +-- AttributeError
      +-- BufferError
      +-- EOFError
      +-- ImportError
      |    +-- ModuleNotFoundError
      +-- LookupError
      |    +-- IndexError
      |    +-- KeyError
      +-- MemoryError
      +-- NameError
      |    +-- UnboundLocalError
      +-- OSError
      |    +-- BlockingIOError
      |    +-- ChildProcessError
      |    +-- ConnectionError
      |    |    +-- BrokenPipeError
      |    |    +-- ConnectionAbortedError
      |    |    +-- ConnectionRefusedError
      |    |    +-- ConnectionResetError
      |    +-- FileExistsError
      |    +-- FileNotFoundError
      |    +-- InterruptedError
      |    +-- IsADirectoryError
      |    +-- NotADirectoryError
      |    +-- PermissionError
      |    +-- ProcessLookupError
      |    +-- TimeoutError
      +-- ReferenceError
      +-- RuntimeError
      |    +-- NotImplementedError
      |    +-- RecursionError
      +-- SyntaxError
      |    +-- IndentationError
      |         +-- TabError
      +-- SystemError
      +-- TypeError
      +-- ValueError
      |    +-- UnicodeError
      |         +-- UnicodeDecodeError
      |         +-- UnicodeEncodeError
      |         +-- UnicodeTranslateError
      +-- Warning
           +-- DeprecationWarning
           +-- PendingDeprecationWarning
           +-- RuntimeWarning
           +-- SyntaxWarning
           +-- UserWarning
           +-- FutureWarning
           +-- ImportWarning
           +-- UnicodeWarning
           +-- BytesWarning
           +-- ResourceWarning

Прежде чем переходить к разбору встроенных исключений быстро вспомним 4 основных компонента обработки исключения, как показано на этой схеме.

  • Try: он запускает блок кода, в котором ожидается ошибка.
  • Except: здесь определяется тип исключения, который ожидается в блоке try (встроенный или созданный).
  • Else: если исключений нет, тогда исполняется этот блок (его можно воспринимать как средство для запуска кода в том случае, если ожидается, что часть кода приведет к исключению).
  • Finally: вне зависимости от того, будет ли исключение или нет, этот блок кода исполняется всегда.

В следующем разделе руководства больше узнаете об общих типах исключений и научитесь обрабатывать их с помощью инструмента обработки исключения.

Ошибка прерывания с клавиатуры (KeyboardInterrupt)

Исключение KeyboardInterrupt вызывается при попытке остановить программу с помощью сочетания Ctrl + C или Ctrl + Z в командной строке или ядре в Jupyter Notebook. Иногда это происходит неумышленно и подобная обработка поможет избежать подобных ситуаций.

В примере ниже если запустить ячейку и прервать ядро, программа вызовет исключение KeyboardInterrupt. Теперь обработаем исключение KeyboardInterrupt.

try:
    inp = input()
    print('Нажмите Ctrl+C и прервите Kernel:')
except KeyboardInterrupt:
    print('Исключение KeyboardInterrupt')
else:
    print('Исключений не произошло')

Исключение KeyboardInterrupt

Стандартные ошибки (StandardError)

Рассмотрим некоторые базовые ошибки в программировании.

Арифметические ошибки (ArithmeticError)

  • Ошибка деления на ноль (Zero Division);
  • Ошибка переполнения (OverFlow);
  • Ошибка плавающей точки (Floating Point);

Все перечисленные выше исключения относятся к классу Arithmetic и вызываются при ошибках в арифметических операциях.

Деление на ноль (ZeroDivisionError)

Когда делитель (второй аргумент операции деления) или знаменатель равны нулю, тогда результатом будет ошибка деления на ноль.

try:  
    a = 100 / 0
    print(a)
except ZeroDivisionError:  
    print("Исключение ZeroDivisionError." )
else:  
    print("Успех, нет ошибок!")
Исключение ZeroDivisionError.

Переполнение (OverflowError)

Ошибка переполнение вызывается, когда результат операции выходил за пределы диапазона. Она характерна для целых чисел вне диапазона.

try:  
    import math
    print(math.exp(1000))
except OverflowError:  
    print("Исключение OverFlow.")
else:  
    print("Успех, нет ошибок!")
Исключение OverFlow.

Ошибка утверждения (AssertionError)

Когда инструкция утверждения не верна, вызывается ошибка утверждения.

Рассмотрим пример. Предположим, есть две переменные: a и b. Их нужно сравнить. Чтобы проверить, равны ли они, необходимо использовать ключевое слово assert, что приведет к вызову исключения Assertion в том случае, если выражение будет ложным.

try:  
    a = 100
    b = "PythonRu"
    assert a == b
except AssertionError:  
    print("Исключение AssertionError.")
else:  
    print("Успех, нет ошибок!")

Исключение AssertionError.

Ошибка атрибута (AttributeError)

При попытке сослаться на несуществующий атрибут программа вернет ошибку атрибута. В следующем примере можно увидеть, что у объекта класса Attributes нет атрибута с именем attribute.

class Attributes(obj):
    a = 2
    print(a)

try:
    obj = Attributes()
    print(obj.attribute)
except AttributeError:
    print("Исключение AttributeError.")

2
Исключение AttributeError.

Ошибка импорта (ModuleNotFoundError)

Ошибка импорта вызывается при попытке импортировать несуществующий (или неспособный загрузиться) модуль в стандартном пути или даже при допущенной ошибке в имени.

import nibabel
---------------------------------------------------------------------------

ModuleNotFoundError                       Traceback (most recent call last)

 in 
----> 1 import nibabel


ModuleNotFoundError: No module named 'nibabel'

Ошибка поиска (LookupError)

LockupError выступает базовым классом для исключений, которые происходят, когда key или index используются для связывания или последовательность списка/словаря неверна или не существует.

Здесь есть два вида исключений:

  • Ошибка индекса (IndexError);
  • Ошибка ключа (KeyError);

Ошибка ключа

Если ключа, к которому нужно получить доступ, не оказывается в словаре, вызывается исключение KeyError.

try:  
    a = {1:'a', 2:'b', 3:'c'}  
    print(a[4])  
except LookupError:  
    print("Исключение KeyError.")
else:  
    print("Успех, нет ошибок!")

Исключение KeyError.

Ошибка индекса

Если пытаться получить доступ к индексу (последовательности) списка, которого не существует в этом списке или находится вне его диапазона, будет вызвана ошибка индекса (IndexError: list index out of range python).

try:
    a = ['a', 'b', 'c']  
    print(a[4])  
except LookupError:  
    print("Исключение IndexError, индекс списка вне диапазона.")
else:  
    print("Успех, нет ошибок!")
Исключение IndexError, индекс списка вне диапазона.

Ошибка памяти (MemoryError)

Как уже упоминалось, ошибка памяти вызывается, когда операции не хватает памяти для выполнения.

Ошибка имени (NameError)

Ошибка имени возникает, когда локальное или глобальное имя не находится.

В следующем примере переменная ans не определена. Результатом будет ошибка NameError.

try:
    print(ans)
except NameError:  
    print("NameError: переменная 'ans' не определена")
else:  
    print("Успех, нет ошибок!")
NameError: переменная 'ans' не определена

Ошибка выполнения (Runtime Error)

Ошибка «NotImplementedError»
Ошибка выполнения служит базовым классом для ошибки NotImplemented. Абстрактные методы определенного пользователем класса вызывают это исключение, когда производные методы перезаписывают оригинальный.

class BaseClass(object):
    """Опередляем класс"""
    def __init__(self):
        super(BaseClass, self).__init__()
    def do_something(self):
	# функция ничего не делает
        raise NotImplementedError(self.__class__.__name__ + '.do_something')

class SubClass(BaseClass):
    """Реализует функцию"""
    def do_something(self):
        # действительно что-то делает
        print(self.__class__.__name__ + ' что-то делает!')

SubClass().do_something()
BaseClass().do_something()

SubClass что-то делает!



---------------------------------------------------------------------------

NotImplementedError                       Traceback (most recent call last)

 in 
     14
     15 SubClass().do_something()
---> 16 BaseClass().do_something()


 in do_something(self)
      5     def do_something(self):
      6         # функция ничего не делает
----> 7         raise NotImplementedError(self.__class__.__name__ + '.do_something')
      8
      9 class SubClass(BaseClass):


NotImplementedError: BaseClass.do_something

Ошибка типа (TypeError)

Ошибка типа вызывается при попытке объединить два несовместимых операнда или объекта.

В примере ниже целое число пытаются добавить к строке, что приводит к ошибке типа.

try:
    a = 5
    b = "PythonRu"
    c = a + b
except TypeError:
    print('Исключение TypeError')
else:
    print('Успех, нет ошибок!')

Исключение TypeError

Ошибка значения (ValueError)

Ошибка значения вызывается, когда встроенная операция или функция получают аргумент с корректным типом, но недопустимым значением.

В этом примере встроенная операция float получат аргумент, представляющий собой последовательность символов (значение), что является недопустимым значением для типа: число с плавающей точкой.

try:
    print(float('PythonRu'))
except ValueError:
    print('ValueError: не удалось преобразовать строку в float: 'PythonRu'')
else:
    print('Успех, нет ошибок!')
ValueError: не удалось преобразовать строку в float: 'PythonRu'

Пользовательские исключения в Python

В Python есть много встроенных исключений для использования в программе. Но иногда нужно создавать собственные со своими сообщениями для конкретных целей.

Это можно сделать, создав новый класс, который будет наследовать из класса Exception в Python.

class UnAcceptedValueError(Exception):   
    def __init__(self, data):    
        self.data = data
    def __str__(self):
        return repr(self.data)

Total_Marks = int(input("Введите общее количество баллов: "))
try:
    Num_of_Sections = int(input("Введите количество разделов: "))
    if(Num_of_Sections < 1):
        raise UnAcceptedValueError("Количество секций не может быть меньше 1")
except UnAcceptedValueError as e:
    print("Полученная ошибка:", e.data)

Введите общее количество баллов: 10
Введите количество разделов: 0
Полученная ошибка: Количество секций не может быть меньше 1

В предыдущем примере если ввести что-либо меньше 1, будет вызвано исключение. Многие стандартные исключения имеют собственные исключения, которые вызываются при возникновении проблем в работе их функций.

Недостатки обработки исключений в Python

У использования исключений есть свои побочные эффекты, как, например, то, что программы с блоками try-except работают медленнее, а количество кода возрастает.

Дальше пример, где модуль Python timeit используется для проверки времени исполнения 2 разных инструкций. В stmt1 для обработки ZeroDivisionError используется try-except, а в stmt2if. Затем они выполняются 10000 раз с переменной a=0. Суть в том, чтобы показать разницу во времени исполнения инструкций. Так, stmt1 с обработкой исключений занимает больше времени чем stmt2, который просто проверяет значение и не делает ничего, если условие не выполнено.

Поэтому стоит ограничить использование обработки исключений в Python и применять его в редких случаях. Например, когда вы не уверены, что будет вводом: целое или число с плавающей точкой, или не уверены, существует ли файл, который нужно открыть.

import timeit
setup="a=0"
stmt1 = '''
try:
    b=10/a
except ZeroDivisionError:
    pass'''

stmt2 = '''
if a!=0:
    b=10/a'''

print("time=",timeit.timeit(stmt1,setup,number=10000))
print("time=",timeit.timeit(stmt2,setup,number=10000))

time= 0.003897680000136461
time= 0.0002797570000439009

Выводы!

Как вы могли увидеть, обработка исключений помогает прервать типичный поток программы с помощью специального механизма, который делает код более отказоустойчивым.

Обработка исключений — один из основных факторов, который делает код готовым к развертыванию. Это простая концепция, построенная всего на 4 блоках: try выискивает исключения, а except их обрабатывает.

Очень важно поупражняться в их использовании, чтобы сделать свой код более отказоустойчивым.

Python f-strings are impressive!

Did you know you can use f-strings to string format almost anything in Python?

You can use them to format floats, multiline strings, decimal places, objects and even use if-else conditionals within them.

In this post, I’ll show you at least 73 examples on how to format strings using Python 3’s f-strings. You’ll see the many ways you can take advantage of this powerful feature.

By the end of this guide, you’ll have mastered:

  • how to use f string to format float numbers
  • how to format multiline string
  • how to define decimal places in a f-string
  • how to fix invalid syntax errors such as «syntaxerror: f-string: unmatched ‘[‘» or f-string: unmatched ‘(‘
  • how to use if else statement in a f-string
  • basic string interpolation formatting using f-strings
  • how to print f-strings
  • how to effectively add padding using fstring

Let’s go!

Table of Contents

  1. What Are Python 3’s F-Strings — a.k.a Literal String Interpolation?
  2. How to Format Strings in Python 3 — The Basics
  3. Limitations
  4. How to Format an Expression
  5. How to Use F-Strings to Debug Your Code
  6. How to Format a Multiline F-String (Dealing with New Lines and Variables)
  7. How to Fix F-String’s Invalid Syntax Error
  8. How to Fix «formatting a regular string which could be a f-string»
  9. How to Format Numbers in Different Bases
  10. How to Print Formatted Objects With F-Strings
  11. How to Use F-Strings to Format a Float
  12. How to Format a Number as Percentage
  13. How to Justify or Add Padding to a F-String
  14. How to Escape Characters With f-string
  15. How to Add a Thousand Separator

    15.1. How to Format a Number With Commas as Decimal Separator

    15.2. How to Format a Number With Spaces as Decimal Separator

  16. How to Format a Number in Scientific Notation (Exponential Notation)
  17. Using if-else Conditional in a F-String
  18. How to Use F-String With a Dictionary
  19. How to Concatenate F-Strings
  20. How to Format a Date With F-String
  21. How to Add Leading Zeros
  22. Conclusion

What Are Python F-Strings — a.k.a Literal String Interpolation?

String formatting has evolved quite a bit in the history of Python. Before Python 2.6, to format a string, one would either use the % operator, or string.Template module. Some time later, the str.format method came along and added to the language a more flexible and robust way of formatting a string.

Old string formatting with %:

>>> msg = 'hello world'
>>> 'msg: %s' % msg
'msg: hello world'

Using string.format:

>>> msg = 'hello world'
>>> 'msg: {}'.format(msg)
'msg: hello world'

To simplify formatting even further, in 2015, Eric Smith proposed the
PEP 498 — Literal String Interpolation
, a new way to format a string for python 3.

PEP 498 presented this new string interpolation to be a simple and easy to use alternative to str.format. The only thing required is to put a ‘f’ before a string. And if you’re new to the language, that’s what f in Python means, it’s a new syntax to create formatted strings.

Using f-strings:

>>> msg = 'hello world'
>>> f'msg: {msg}'
'msg: hello world'

And that was it! No need to use str.format or %. However, f-strings don’t replace str.format completely. In this guide I’ll show you an example where they are not suitable.

How to Format Strings in Python 3 — The Basics

As I have shown in the previous section, formatting strings in python using f-strings is quite straightforward. The sole requirement is to provide it a valid expression. f-strings can also start with capital F and you can combine with raw strings to produce a formatted output. However, you cannot mix them with bytes b"" or "u".

fig_5.png

>>> book = "The dog guide"

>>> num_pages = 124

>>> f"The book {book} has {num_pages} pages"
'The book The dog guide has 124 pages'

>>> F"The book {book} has {num_pages} pages"
'The book The dog guide has 124 pages'

>>> print(Fr"The book {book} has {num_pages} pagesn")
The book The dog guide has 124 pagesn

>>> print(FR"The book {book} has {num_pages} pagesn")
The book The dog guide has 124 pagesn

>>> print(f"The book {book} has {num_pages} pagesn")
The book The dog guide has 124 pages

And that’s pretty much it! In the next section, I’ll show you several examples of everything you can do — and cannot do — with f-strings.

Limitations

Even though f-strings are very convenient, they don’t replace str.format completely. f-strings evaluate expressions in the context where they appear. According the the PEP 498
, this means the expression has full access to local and global variables. They’re also an expression evaluated at runtime. If the expression used inside the { <expr> } cannot be evaluated, the interpreter will raise an exception.

>>> f"{name}"
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-f0acc441190f> in <module>
----> 1 f"{name}"

NameError: name 'name' is not defined

This is not a problem for the str.format method, as you can define the template string and then call .format to pass on the context.

>>> s = "{name}"

>>> s.format(name="Python")
'Python'

>>> print(s)
{name}

Another limitation is that you cannot use inline comments inside a f-string.

>>> f"My name is {name #name}!"
  File "<ipython-input-37-0ae1738dd871>", line 1
    f"My name is {name #name}!"
    ^
SyntaxError: f-string expression part cannot include '#'

How to Format an Expression

If you don’t want to define variables, you can use literals inside the brackets. Python will evaluate the expression and display the final result.

>>> f"4 * 4 is {4 * 4}"
'4 * 4 is 16'

Or if you prefer…

>>> n = 4

>>> f"4 * 4 is {n * n}"
'4 * 4 is 16'

How to Use F-Strings to Debug Your Code

One of most frequent usages of f-string is debugging. Before Python 3.8, many people would do hello = 42; f"hello = {hello}", but this is very repetitive. As a result, Python 3.8 brought a new feature. You can re-write that expression as f"{hello=}" and Python will display hello=42. The following example illustrates this using a function, but the principle is the same.

>>> def magic_number():
     ...:     return 42
     ...: 

>>> f"{magic_number() = }"
'magic_number() = 42'

How to Format a Multiline F-String (Dealing with New Lines and Variables)

You can use the newline character n with f-strings to print a string in multiple lines.

>>> multi_line = (f'R: {color["R"]}nG: {color["G"]}nB: {color["B"
    ...: ]}n')

>>> multi_line
'R: 123nG: 145nB: 255n'

>>> print(multi_line)
R: 123
G: 145
B: 255

As an alternative, you can use triple quotes to represent the multiline string with variables. It not only allows you to add line breaks, it’s also possible to add TAB.

>>> other = f"""R: {color["R"]}
    ...: G: {color["G"]}
    ...: B: {color["B"]}
    ...: """

>>> print(other)
R: 123
G: 145
B: 255

Example with TABs.

>>> other = f'''
    ...: this is an example
    ...: 
    ...: ^Iof color {color["R"]}
    ...:     
    ...: '''

>>> other
'nthis is an examplenntof color 123n    n'

>>> print(other)

this is an example

    of color 123



>>>

How to Fix F-String’s Invalid Syntax Error

If not used correctly, f-strings can raise a SyntaxError. The most common cause is using double-quotes inside a double quoted f-string. The same is also true for single quotes.

>>> color = {"R": 123, "G": 145, "B": 255}

>>> f"{color["R"]}"
  File "<ipython-input-43-1a7f5d512400>", line 1
    f"{color["R"]}"
    ^
SyntaxError: f-string: unmatched '['


# using only single quotes
>>> f'{color['R']}'
  File "<ipython-input-44-3499a4e3120c>", line 1
    f'{color['R']}'
    ^
SyntaxError: f-string: unmatched '['

This error not only happens with '[', but also '('. The cause is the same, it happens when you close a quote prematurely.

>>> print(f"price: {format(round(12.345), ",")}")
  File "<ipython-input-2-1ae6f786bc4d>", line 1
    print(f"price: {format(round(12.345), ",")}")
                                           ^
SyntaxError: f-string: unmatched '('

To fix that, you need to use single quotes.

>>> print(f"price: {format(round(12.345), ',')}")
price: 12

>>> color = {"R": 123, "G": 145, "B": 255}

>>> f"{color['R']}"
'123'

>>> f'{color["R"]}'
'123'

Another common case is to use f-strings in older versions of Python. f-strings were introduced in Python 3.6. If you use it in an older version, the interpreter will raise a SyntaxError: invalid syntax.

>>> f"this is an old version"
  File "<stdin>", line 1
    f"this is an old verion"
                            ^
SyntaxError: invalid syntax

If you see invalid syntax, make sure to double check the Python version you are running. In my case, I tested in on Python 2.7, and you can find the version by calling sys.version.

>>> import sys; print(sys.version)
2.7.18 (default, Apr 20 2020, 19:27:10) 
[GCC 8.3.0]

How to Fix «formatting a regular string which could be a f-string»

This error happens because pylint detects the old way of formatting string such as using % or the str.format method.

C0209: Formatting a regular string which could be a f-string (consider-using-f-string)

To fix that you can either:

  • replace the old formatting method with a f-string
  • ignore the pylint error using

In this post, I explain how to fix this issue step-by-step.

Replacing with f-strings

The following examples illustrate how to convert old method to f-string.

>>>  ip_address = "127.0.0.1"

# pylint complains if we use the methods below
>>> "http://%s:8000/" % ip_address
'http://127.0.0.1:8000/'

>>> "http://{}:8000/".format(ip_address)
'http://127.0.0.1:8000/'

# Replace it with a f-string
>>> f"http://{ip_address}:8000/"
'http://127.0.0.1:8000/'

Disable pylint

Alternatively, you can disable pylint by specifying the «disable» flag with the error code.

>>>  ip_address = "127.0.0.1"

# pylint complains if we use the methods below, so we can disable them
>>> "http://%s:8000/" % ip_address  # pylint: disable=C0209
'http://127.0.0.1:8000/'

>>> "http://{}:8000/".format(ip_address)  # pylint: disable=C0209
'http://127.0.0.1:8000/'

Another way of disabling that error is to add it to the .pylintrc file.

# .pylintrc
disable=
    ...
    consider-using-f-string,
    ...

There’s yet another way of disabling it, which is by placing a comment at the top of the file, like so:

 # pylint: disable=consider-using-f-string

def your_function(fun):
    """Your code below"""
    ...

How to Format Numbers in Different Bases

fig_6.png

f-strings also allow you to display an integer in different bases. For example, you can display an int as binary without converting it by using the b option.

>>> f'{7:b}'
'111'

In summary, you can use f-strings to format:

  • int to binary
  • int to hex
  • int to octal
  • int to HEX (where all chars are capitalized)

The following example uses the padding feature and the base formatting to create a table that displays an int in other bases.

>>> bases = {
       "b": "bin", 
       "o": "oct", 
       "x": "hex", 
       "X": "HEX", 
       "d": "decimal"
}
>>> for n in range(1, 21):
     ...:     for base, desc in bases.items():
     ...:         print(f"{n:5{base}}", end=' ')
     ...:     print()

    1     1     1     1     1 
   10     2     2     2     2 
   11     3     3     3     3 
  100     4     4     4     4 
  101     5     5     5     5 
  110     6     6     6     6 
  111     7     7     7     7 
 1000    10     8     8     8 
 1001    11     9     9     9 
 1010    12     a     A    10 
 1011    13     b     B    11 
 1100    14     c     C    12 
 1101    15     d     D    13 
 1110    16     e     E    14 
 1111    17     f     F    15 
10000    20    10    10    16 
10001    21    11    11    17 
10010    22    12    12    18 
10011    23    13    13    19 
10100    24    14    14    20

How to Print Formatted Objects With F-Strings

You can print custom objects using f-strings. By default, when you pass an object instance to a f-string, it will display what the __str__ method returns. However, you can also use the explicit conversion flag to display the __repr__.

!r - converts the value to a string using repr().
!s - converts the value to a string using str().
>>> class Color:
    def __init__(self, r: float = 255, g: float = 255, b: float = 255):
        self.r = r
        self.g = g
        self.b = b

    def __str__(self) -> str:
        return "A RGB color"

    def __repr__(self) -> str:
        return f"Color(r={self.r}, g={self.g}, b={self.b})"

>>> c = Color(r=123, g=32, b=255)

# When no option is passed, the __str__ result is printed
>>> f"{c}"
'A RGB color'

# When `obj!r` is used, the __repr__ output is printed
>>> f"{c!r}"
'Color(r=123, g=32, b=255)'

# Same as the default
>>> f"{c!s}"
'A RGB color'

Python also allows us to control the formatting on a per-type basis through the __format__ method. The following example shows how you can do all of that.

>>> class Color:
    def __init__(self, r: float = 255, g: float = 255, b: float = 255):
        self.r = r
        self.g = g
        self.b = b

    def __str__(self) -> str:
        return "A RGB color"

    def __repr__(self) -> str:
        return f"Color(r={self.r}, g={self.g}, b={self.b})"

    def __format__(self, format_spec: str) -> str:
        if not format_spec or format_spec == "s":
            return str(self)

        if format_spec == "r":
            return repr(self)

        if format_spec == "v":
            return f"Color(r={self.r}, g={self.g}, b={self.b}) - A nice RGB thing."

        if format_spec == "vv":
            return (
                f"Color(r={self.r}, g={self.g}, b={self.b}) "
                f"- A more verbose nice RGB thing."
            )

        if format_spec == "vvv":
            return (
                f"Color(r={self.r}, g={self.g}, b={self.b}) "
                f"- A SUPER verbose nice RGB thing."
            )

        raise ValueError(
            f"Unknown format code '{format_spec}' " "for object of type 'Color'"
        )

>>> c = Color(r=123, g=32, b=255)

>>> f'{c:v}'
'Color(r=123, g=32, b=255) - A nice RGB thing.'

>>> f'{c:vv}'
'Color(r=123, g=32, b=255) - A more verbose nice RGB thing.'

>>> f'{c:vvv}'
'Color(r=123, g=32, b=255) - A SUPER verbose nice RGB thing.'

>>> f'{c}'
'A RGB color'

>>> f'{c:s}'
'A RGB color'

>>> f'{c:r}'
'Color(r=123, g=32, b=255)'

>>> f'{c:j}'
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-20-1c0ee8dd74be> in <module>
----> 1 f'{c:j}'

<ipython-input-15-985c4992e957> in __format__(self, format_spec)
     29                 f"- A SUPER verbose nice RGB thing."
     30             )
---> 31         raise ValueError(
     32             f"Unknown format code '{format_spec}' " "for object of type 'Color'"
     33         )

ValueError: Unknown format code 'j' for object of type 'Color'

Lastly, there’s also the a option that escapes non-ASCII chars. For more info: docs.python.org/3/library/functions.html#as..

>>> utf_str = "Áeiöu"

>>> f"{utf_str!a}"
"'\xc1ei\xf6u'"

How to Use F-Strings to Format a Float

f-strings allow format float numbers similar to str.format method. To do that, you can add a : (colon) followed by a . (dot) and the number of decimal places with a f suffix.

For instance, you can round a float to 2 decimal places and print the variable just like this:

>>> num = 4.123956

>>> f"num rounded to 2 decimal places = {num:.2f}"
'num rounded to 2 decimal places = 4.12'

If you don’t specify anything, the float variable will use the full precision.

>>> print(f'{num}')
4.123956

How to Format a Number as Percentage

Python f-strings have a very convenient way of formatting percentage. The rules are similar to float formatting, except that you append a % instead of f. It multiplies the number by 100 displaying it in a fixed format, followed by a percent sign. You can also specify the precision.

>>> total = 87

>>> true_pos = 34

>>> perc = true_pos / total

>>> perc
0.39080459770114945

>>> f"Percentage of true positive: {perc:%}"
'Percentage of true positive: 39.080460%'

>>> f"Percentage of true positive: {perc:.2%}"
'Percentage of true positive: 39.08%'

How to Justify or Add Padding to a F-String

You can justify a string quite easily using < or > characters.

how to justify or add padding to a string in python

>>> greetings = "hello"

>>> f"She says {greetings:>10}"
'She says      hello'

# Pad 10 char to the right
>>> f"{greetings:>10}"
'     hello'

>>> f"{greetings:<10}"
'hello     '

# You can omit the < for left padding
>>> f"{greetings:10}"
'hello     '

fig_2.png

>>> a = "1"

>>> b = "21"

>>> c = "321"

>>> d = "4321"

>>> print("n".join((f"{a:>10}", f"{b:>10}", f"{c:>10}", f"{d:>10}")))
         1
        21
       321
      4321

How to Escape Characters With f-string

In case you want to display the variable name surrounded by the curly brackets instead of rendering its value, you can escape it using double {{<expr>}}.

>>> hello = "world"

>>> f"{{hello}} = {hello}"
'{hello} = world'

Now, if you want to escape a double quote, you can use the backslash ".

>>> f"{hello} = "hello""
'world = "hello"'

How to Center a String

fig_1.png

Centering a string can be achieved by using var:^N where var is a variable you want to display and N is the string length. If N is shorter than the var, then Python display the whole string.

>>> hello = "world"

>>> f"{hello:^11}"
'   world   '

>>> f"{hello:*^11}"
'***world***'

# Extra padding is added to the right
>>> f"{hello:*^10}"
'**world***'

# N shorter than len(hello)
>>> f"{hello:^2}"
'world'

How To Add a Thousand Separator

fig_4.png

f-strings also allow us to customize numbers. One common operation is to add an underscore to separate every thousand place.

>>> big_num = 1234567890

>>> f"{big_num:_}"
'1_234_567_890'

How to Format a Number With Commas as Decimal Separator

In fact, you can use any char as separator. It’s also possible to use a comma as separator.

>>> big_num = 1234567890

>>> f"{big_num:,}"
'1,234,567,890'

You can also format a float with commas and set the precision in one go.

>>> num = 2343552.6516251625

>>> f"{num:,.3f}"
'2,343,552.652'

How to Format a Number With Spaces as Decimal Separator

What about using spaces instead?

Well, this one is a bit “hacky” but it works. You can use the , as separator, then replace it with space.

>>> big_num = 1234567890

>>> f"{big_num:,}".replace(',', ' ')
'1 234 567 890'

Another option is to set the locale of your environment to one that uses spaces as a thousand separator such as pl_PL. For more info, see this thread on stack overflow.

How to Format a Number in Scientific Notation (Exponential Notation)

Formatting a number in scientific notation is possible with the e or E option.

>>> num = 2343552.6516251625

>>> f"{num:e}"
'2.343553e+06'

>>> f"{num:E}"
'2.343553E+06'

>>> f"{num:.2e}"
'2.34e+06'

>>> f"{num:.4E}"
'2.3436E+06'

Using if-else Conditional in a F-String

f-strings also evaluates more complex expressions such as inline if/else.

>>> a = "this is a"

>>> b = "this is b"

>>> f"{a if 10 > 5 else b}"
'this is a'

>>> f"{a if 10 < 5 else b}"
'this is b'

How to Use F-String With a Dictionary

You can use dictionaries in a f-string. The only requirement is to use a different quotation mark than the one enclosing the expression.

>>> color = {"R": 123, "G": 145, "B": 255}

>>> f"{color['R']}"
'123'

>>> f'{color["R"]}'
''123'

>>> f"RGB = ({color['R']}, {color['G']}, {color['B']})"
'RGB = (123, 145, 255)'

How to Concatenate F-Strings

Concatenating f-strings is like concatenating regular strings, you can do that implicitly, or explicitly by applying the + operator or using str.join method.

# Implicit string concatenation
>>> f"{123}" " = " f"{100}" " + " f"{20}" " + " f"{3}"
'123 = 100 + 20 + 3'

# Explicity concatenation using '+' operator
>>> f"{12}" + " != " + f"{13}"
'12 != 13'

# string concatenation using `str.join`
>>> " ".join((f"{13}", f"{45}"))
'13 45'

>>> "#".join((f"{13}", f"{45}"))
'13#45'

How to Format a Date With F-String

f-strings also support the formatting of datetime objects. The process is very similar to how str.format formats dates. For more info about the supported formats, check this table in the official docs.

fig_7.png

>>> import datetime

>>> now = datetime.datetime.now()

>>> ten_days_ago = now - datetime.timedelta(days=10)

>>> f'{ten_days_ago:%Y-%m-%d %H:%M:%S}'
'2020-10-13 20:24:17'

>>> f'{now:%Y-%m-%d %H:%M:%S}'
'2020-10-23 20:24:17'

How to Add Leading Zeros

You can add leading zeros by adding using the format {expr:0len} where len is the length of the returned string. You can include a sign option. In this instance, + means the sign should be used for positive and negative numbers. The - is used only for negative numbers, which is the default behavior. For more info, check the string format specification page .

>>> num = 42

>>> f"{num:05}"
'00042'

>>> f'{num:+010}'
'+000000042'

>>> f'{num:-010}'
'0000000042'

>>> f"{num:010}"
'0000000042'

>>> num = -42

>>> f'{num:+010}'
'-000000042'

>>> f'{num:010}'
'-000000042'

>>> f'{num:-010}'
'-000000042'

Conclusion

That’s it for today, folks! I hope you’ve learned something different and useful. Knowing how to make the most out of f-string can make our lives so much easier. In this post, I showed the most common tricks I use in a day-to-day basis.

Other posts you may like:

  • How to Check if an Exception Is Raised (or Not) With pytest
  • Everything You Need to Know About Python’s Namedtuples
  • The Best Way to Compare Two Dictionaries in Python
  • 11 Useful Resources To Learn Python’s Internals From Scratch
  • 7 pytest Features and Plugins That Will Save You Tons of Time

See you next time!

Понравилась статья? Поделить с друзьями:
  • Unmatched data error mql4
  • Unmarshalling перевод error
  • Unmarshalling request error детали employment must be present at request
  • Unmarshalling error unexpected element uri
  • Unmarshalling error for input string