Skip to content

Commit fbd3fcb

Browse files
committed
Refactoring. Using f-strings
1 parent 04260cb commit fbd3fcb

File tree

17 files changed

+28
-34
lines changed

17 files changed

+28
-34
lines changed

Diff for: Damerau–Levenshtein_distance__misprints__опечатки/use__pyxdameraulevenshtein/fix_command.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ def check(text):
6868

6969
command = fix_command(text)
7070
if command is None:
71-
result = 'is None (не удалось распознать команду: "{}")'.format(text)
71+
result = f'is None (не удалось распознать команду: "{text}")'
7272
print(format_text.format(text, result))
7373
else:
7474
print(format_text.format(text, command))
@@ -98,9 +98,7 @@ def check(text):
9898
def run_tests():
9999
def test(text, expected):
100100
command = fix_command(text)
101-
assert expected == command, 'Expected: "{}", get: "{}"'.format(
102-
expected, command
103-
)
101+
assert expected == command, f'Expected: "{expected}", get: "{command}"'
104102

105103
expected = "команды"
106104
test("команды", expected)

Diff for: Decorators__examples/example_1.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ def getprint(str="hello world!"):
88
def decor(func):
99
def wrapper(*args, **kwargs):
1010
print("1 begin: " + func.__name__)
11-
print("Args={} kwargs={}".format(args, kwargs))
11+
print(f"Args={args} kwargs={kwargs}")
1212
f = func(*args, **kwargs)
1313
print("2 end: " + func.__name__ + "\n")
1414
return f
@@ -31,7 +31,7 @@ def predecor(w="W"):
3131
def rgb2hex(get_rgb_func):
3232
def wrapper(*args, **kwargs):
3333
r, g, b = get_rgb_func(*args, **kwargs)
34-
return "#{:02x}{:02x}{:02x}".format(r, g, b)
34+
return f"#{r:02x}{g:02x}{b:02x}"
3535

3636
return wrapper
3737

@@ -75,15 +75,15 @@ def getrgb(self):
7575

7676

7777
rgb = RGB()
78-
print("rgb.r={}".format(rgb.r))
78+
print(f"rgb.r={rgb.r}")
7979
rgb.setrgb(0xFF, 0x1, 0xFF)
80-
print("rgb.getrgb(): %s" % rgb.getrgb())
80+
print(f"rgb.getrgb(): {rgb.getrgb()}")
8181
print()
8282

8383

8484
@decor
8585
def foo(a, b):
86-
print("{} ^ {} = {}".format(a, b, (a**b)))
86+
print(f"{a} ^ {b} = {(a ** b)}")
8787

8888

8989
foo(2, 3)

Diff for: Environment variables/EnvironmentVariables.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99

1010
# Вывести все переменные окружения (environment variables)
11-
print("Environment variables:\n{}".format(os.environ))
11+
print(f"Environment variables:\n{os.environ}")
1212

1313
print("\nEnvironment variables:")
1414
for var, value in os.environ.items():

Diff for: EscapePyPromptLineString/main.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ def input_text_changed(self):
112112
out_text = "\n".join(new_out_text)
113113
self.text_edit_output.setPlainText(out_text)
114114

115-
print("Escape for {:.3f} secs".format(time.perf_counter() - t))
115+
print(f"Escape for {time.perf_counter() - t:.3f} secs")
116116

117117
except Exception as e:
118118
# Выводим ошибку в консоль

Diff for: EscapeString/main.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -200,7 +200,7 @@ def input_text_changed(self):
200200
f"{len(self.text_edit_input.toPlainText())} -> "
201201
f"{len(self.text_edit_output.toPlainText())})"
202202
)
203-
print("Escape for {:.6f} secs".format(time.perf_counter() - t))
203+
print(f"Escape for {time.perf_counter() - t:.6f} secs")
204204

205205
except Exception as e:
206206
# Выводим ошибку в консоль

Diff for: design_patterns__examples/Builder/example2.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,7 @@ def get_value(self, key):
2525
return self.key_by_value[key]
2626

2727
def __repr__(self):
28-
return "Foo<items={}, values={}>".format(
29-
len(self.items), len(self.key_by_value)
30-
)
28+
return f"Foo<items={len(self.items)}, values={len(self.key_by_value)}>"
3129

3230

3331
foo = Foo().add_item(1).add_items("abc").set_value("x", 1).set_value("x[]", [1, 2, 3])

Diff for: design_patterns__examples/Builder/example_wok.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,7 @@ def get_order_text(self) -> str:
160160
for item in self.get_order_items():
161161
text += f" {item.name:25} : {item.price} рублей\n"
162162

163-
text += " {:25} : {} рублей".format("", self.get_order_price())
163+
text += f" {'':25} : {self.get_order_price()} рублей"
164164

165165
return text
166166

Diff for: design_patterns__examples/Observer/example_1.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -83,9 +83,8 @@ def update(self, temperature: float, humidity: float, pressure: int):
8383

8484
def display(self):
8585
print(
86-
"Сейчас значения: {:.1f} градусов цельсия и {:.1f}% влажности. Давление {} мм рт. ст.".format(
87-
self.temperature, self.humidity, self.pressure
88-
)
86+
f"Сейчас значения: {self.temperature:.1f} градусов цельсия и {self.humidity:.1f}% влажности. "
87+
f"Давление {self.pressure} мм рт. ст."
8988
)
9089

9190

Diff for: design_patterns__examples/Proxy/example__cached.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ def __enter__(self):
6666
return self
6767

6868
def __exit__(self, exc_type, exc_value, exc_traceback):
69-
print("Elapsed time: {:.6f} sec".format(time.clock() - self.start_time))
69+
print(f"Elapsed time: {time.clock() - self.start_time:.6f} sec")
7070

7171
url = "https://github.com/gil9red"
7272

Diff for: design_patterns__examples/Proxy/example__logged.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ def __enter__(self):
7474
return self
7575

7676
def __exit__(self, exc_type, exc_value, exc_traceback):
77-
print("Elapsed time: {:.6f} sec".format(time.clock() - self.start_time))
77+
print(f"Elapsed time: {time.clock() - self.start_time:.6f} sec")
7878

7979
url = "https://github.com/gil9red"
8080

Diff for: design_patterns__examples/Template method/example_1.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -48,15 +48,15 @@ def _move(self, direction: str) -> None:
4848
4949
:param direction: направление движения
5050
"""
51-
self._output("движется {} со скоростью {}".format(direction, self._speed))
51+
self._output(f"движется {direction} со скоростью {self._speed}")
5252

5353
def _output(self, message: str) -> None:
5454
"""
5555
Вспомогательный метод вывода сообщений, в шаблон не входит
5656
5757
:param message: выводимое сообщение
5858
"""
59-
print("Отряд типа {} {}".format(self.__class__.__name__, message))
59+
print(f"Отряд типа {self.__class__.__name__} {message}")
6060

6161

6262
class Archers(Unit):

Diff for: detection_of_site_changes_Unistream/gui.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ def _show_last_diff(self, item):
7272
with open(file_name_b, mode="w", encoding="utf-8") as f:
7373
f.write(file_b_text)
7474

75-
os.system("kdiff3 {} {}".format(file_name_a, file_name_b))
75+
os.system(f"kdiff3 {file_name_a} {file_name_b}")
7676

7777
if os.path.exists(file_name_a):
7878
os.remove(file_name_a)

Diff for: detection_of_site_changes_Unistream/main.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -167,9 +167,7 @@ def __init__(self, new_text, old_text=""):
167167
self.diff = get_diff(old_text, new_text, full=False)
168168

169169
def __repr__(self):
170-
return "<TextRevision(id: {}, datetime: {}, text_hash: {})>".format(
171-
self.id, self.datetime, self.text_hash
172-
)
170+
return f"<TextRevision(id: {self.id}, datetime: {self.datetime}, text_hash: {self.text_hash})>"
173171

174172

175173
def get_session():

Diff for: detection_of_site_changes_Unistream/show_last_diff.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
with open(file_name_b, mode="w", encoding="utf-8") as f:
2626
f.write(file_b.text)
2727

28-
os.system("kdiff3 {} {}".format(file_name_a, file_name_b))
28+
os.system(f"kdiff3 {file_name_a} {file_name_b}")
2929

3030
if os.path.exists(file_name_a):
3131
os.remove(file_name_a)

Diff for: determines the type of image/main.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import glob
88
import imghdr
99

10+
1011
for file_name in glob.glob("img/*.txt"):
1112
img_type = imghdr.what(file_name)
12-
print("{} -> {}".format(file_name, img_type))
13+
print(f"{file_name} -> {img_type}")

Diff for: exchange_rates/cbr_ru.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -61,16 +61,16 @@ def exchange_rate(currency, date_req=None):
6161

6262
date_req = date.today()
6363
value, rate_date = exchange_rate("USD", date_req)
64-
print("{}: USD: {}".format(rate_date, value))
64+
print(f"{rate_date}: USD: {value}")
6565

6666
date_req = date.today() - timedelta(days=1)
6767
value, rate_date = exchange_rate("USD", date_req)
68-
print("{}: USD: {}".format(rate_date, value))
68+
print(f"{rate_date}: USD: {value}")
6969

7070
date_req = date.today() + timedelta(days=1)
7171
value, rate_date = exchange_rate("USD", date_req)
72-
print("{}: USD: {}".format(rate_date, value))
72+
print(f"{rate_date}: USD: {value}")
7373

7474
date_req = date.today() + timedelta(days=2)
7575
value, rate_date = exchange_rate("USD", date_req)
76-
print("{}: USD: {}".format(rate_date, value))
76+
print(f"{rate_date}: USD: {value}")

Diff for: f-strings__formatted string literals__PEP 498/my_example.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ def strange_2(self, text):
4949

5050
@staticmethod
5151
def strange_3(text):
52-
return '"{}"'.format(text)
52+
return f'"{text}"'
5353

5454
def __format__(self, format_spec):
5555
format_spec = format_spec.strip()

0 commit comments

Comments
 (0)