686 questions
1
vote
1
answer
162
views
Why doesn’t this f-string with double quotes raise a SyntaxError in Python 3.13.3?
I'm currently following this Python course course from Harvard.
At the point in the video, the instructor shows that the following code should raise a SyntaxError because of the conflicting double ...
3
votes
2
answers
198
views
Make subclass use custom `__str__` in an f-string
I wrote a subclass of Decimal to represent an amount of money. I wrote a custom __str__ to display the currency along with a sign format. My method works when calling str() but in a f-string somehow ...
1
vote
2
answers
89
views
regex to match uuid4 not working with f-string [duplicate]
Working:
#!/usr/bin/python3
import re
path = "/a/b/c/e72cc82c-e83a-431c-9f63-c8d80eec9307"
if re.match(r"/a/b/c/[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}$&...
2
votes
1
answer
95
views
why is transforming a string to octal value \ooo isnt working when i use an f-string and a variable inside {}?
When using a backslash followed by three integers, Python interprets them as an octal value:
# A backslash followed by three integers will result in an octal value:
txt = "\110\145\154\154\157&...
3
votes
2
answers
72
views
How to reduce verbosity of self-documenting expressions in Python f-strings?
This script:
import numpy as np
a = np.array([2, 3, 1, 9], dtype='i4')
print(a)
print(f'{a=}')
produces:
[2 3 1 9]
a=array([2, 3, 1, 9], dtype=int32)
Is there a way to get just a=[2 3 1 9] from {a=}...
2
votes
1
answer
125
views
Convert numpy float to string
import numpy as np
number = np.float32(0.12345678)
assert str(number) == "0.12345678"
assert f"{number}" == "0.12345678359270096"
Why is this different when converting ...
1
vote
1
answer
66
views
Snakemake expand a string saved in a variable
My question is very simple, but I can't find how to do it in the Snakemake documentation.
Let's say I have a very long string to expand, like :
rule all:
input:
expand("sim_files/test_nGen{ngen}...
3
votes
3
answers
128
views
Combine Python f-string with printf style formatting?
I need to format a command line where some parameters come from simple variables, and others are the result of a longer expression. Python f-strings work well for the variables, and I'm using a printf-...
0
votes
4
answers
158
views
f string vs .format in manipulating a file name
I am trying to manipulate a file name to remove an underscore.
final_name = '{0}{1}{2}_{4}_new'.format(*filename.split('_'))
The filename is something like - 2024_10_10_091530_xyz_new.txt and the ...
0
votes
2
answers
335
views
Pycharm keeps saying there is an unmatched [ in an f-string, but it is matched
for a class I'm trying to write a python program. One of the lines tries to use an f string to report the value of a key ('cost') inside of a dictionary ('espresso') that is inside another dictionary ...
14
votes
4
answers
2k
views
Why do I need another pair of curly braces when using a variable in a format specifier in Python f-strings?
I'm learning how Python f-strings handle formatting and came across this syntax:
a = 5.123
b = 2.456
width = 10
result = f"The result is {(a + b):<{width}.2f}end"
print(result)
This ...
0
votes
3
answers
229
views
Python f-string equivalent of iterable unpacking by print instruction
print can nicely unpack a tuple removing brackets and commas, e.g.
a = (0, -1, 1)
print(*a)
produces 0 -1 1. Trying the same with f-strings fails:
print(f'{*a}')
The closest f-string option I found ...
2
votes
1
answer
865
views
Python datetime format: UTC time zone offset with colon
I'm trying to format a datetime object in Python using either the strftime method or an f-string. I would like to include the time zone offset from UTC with a colon between the hour and minute.
...
0
votes
2
answers
479
views
Mypy throws syntax error for multi-line f-strings, despite code running without error
I'm working with Python 3.12 and recently added mypy type-checking to my project. I've encountered an odd issue where mypy throws a syntax error for certain f-strings in my code, specifically those ...
1
vote
5
answers
191
views
F-string format for conditionally prefixing a value
I want to create an f-string that combines two strings, prepending a '.' character to the second if it is not empty.
reference = "file"
modifier = "read"
print(f"unknown ...
-2
votes
2
answers
147
views
Error in syntax of fstrings in function input() [closed]
I have the following code in Python 3
def inputWithDefault(text:str, default):
result = input(f"{" " * int(len(text))}{default}\r{text}")
return default if not(result is ...
0
votes
1
answer
209
views
Python>=3.8, pylint>=3.2.7 - Why doesn't local pylint raise an `f-string: unmatched '('` error here?
I'm confused as to why a local pylint check ignores the following error, but an apparently identical pylint check as part of a GitHub Actions workflow raises a syntax error.
I have a small Python test ...
1
vote
1
answer
65
views
For loop Teradata insert statement
I am pretty new to Python and looking for some assistance.
I have a large number of Teradaat tables and I am looking to take a single field from each of theose tables and put it into a new table. ...
0
votes
2
answers
108
views
How can I set a python f-string format programmatically?
I would like to set the formatting of a large integer in an fstring programmatically. Specifically, I have an integer that can span several orders of magnitude and I'd like to print it using the ...
0
votes
1
answer
46
views
need a way to update variable to include all input list items, formatted the same way
I'm running a program in python that sends graphql post requests.
The query looks like this, :
var = input("string here")
query = f"""query{{item1(item2:"{var}"){{...
1
vote
1
answer
315
views
Why print(f"{variable = }") in Python 3.12 also prints numpy type?
I noticed, that with Python 3.12 and a numpy.float64 when I simply do a
x = numpy.sqrt(3) # type is <class 'numpy.float64'> now
print(f"{x = }")
# this is printed
>>>x = np....
1
vote
2
answers
98
views
Regex does or does not give an error depending on which REPL is used
Consider the following Python code using the regex library re
import re
re.compile(rf"{''.join(['{c}\\s*' for c in 'qqqq'])}")
I have run it in two different REPLs:
https://www....
0
votes
3
answers
91
views
Difference between format(**locals()) and f-string when using variable as key for dictionaries
I have a string templ with variable part that I have to convert with local variables. Variable part of string have a dictionary cur_cols_dct from which I want to get a single value. Key of a ...
3
votes
3
answers
905
views
Why is format() throwing ValueError: Unknown format code 'f' for object of type 'str' when I'm not inputting a string?
I am using Python 2.7. (Switching to Python 3 for this particular code is not an option, please don't suggest it.) I am writing unit tests for some code.
Here is the relevant piece of code:
class ...
-5
votes
1
answer
3k
views
Unterminated f-string literal [closed]
The following code
message = (
f'Lembrete de que existe uma reserva para amanhã de *{dayAfter}*
{dayAfterCellphone} para a carrinha que estás a usar.'
)
is giving me ...
1
vote
2
answers
124
views
Is there a Python f-string equivalent of C++’s std::quoted?
In C++, the std::quoted stream manipulator produces a quoted and escaped version of a string:
std::string dirPath = "C:\\Documents\\Oval Office Recordings\\Launch Codes.txt";
std::cout <&...
-1
votes
3
answers
99
views
What is the rationale for specifying dynamic width and precision _after_ the argument in str.format?
In C programming language dynamic field width and precision is specified before the argument.
printf("%.*s", 2, "ABCDEF")
Yet when str.format was introduced in Python3.0 in 2008 ...
3
votes
1
answer
1k
views
What does '!a' do in python f-strings? [duplicate]
When messing around in python with the exclamation mark, it said that it has to be followed by either !a, !s, or !r.
What does !a do?
Like can you do this?
f"{"txt"!a}"
What will ...
-1
votes
1
answer
52
views
Return Output from Function on Multiple Lines
I've tried to figure this out on my own, but I'm coming to a dead end. I'm trying to return a string from a function that I created that references amounts derived from a pandas dataframe that was ...
1
vote
2
answers
120
views
Problem with Python f-string formatting of struct_time
I have the following code;
oStat=os.stat(oFile)
print(time.strftime('%H:%M:%S', time.localtime(oStat.st_mtime)))
print(f"{time.localtime(oStat.st_mtime):%H:%M:%S}")
The first print ...
3
votes
2
answers
4k
views
Nested quotes in f-string with Python 3.12 vs older versions [duplicate]
With Python 3.12 I can do the following without error:
a = "abc"
s = f"{a.replace("b", "x")}"
Note the nested " characters.
With Python 3.6 the same will ...
0
votes
0
answers
85
views
Python logging: check if a log will print before doing f-string?
Suppose I have code I want to be able to run in production or verbose mode. In verbose, I want to print debug information that will slow the program down:
import logging
import time
import sys
logging....
-1
votes
1
answer
129
views
Key Error when having spaces and "\n" in multiline f-string
Trying to format SPARQL queries in python using f-strings in order to build different queries from a template,
but i'm getting KeyError when i try to format a multiline string:
query = f'''SELECT ?age
...
0
votes
3
answers
202
views
What is a simple way to round all floats in an f-string to the same number of digits in one step?
I have a long f-string with containing many float values, all of which I want to round to the same number of digits. Is there a way to do this in one go or in a smart way, or do I need to specify the ...
-2
votes
1
answer
194
views
Use f-string instead of format call [duplicate]
The server I'm posting ym data to doesn't seem to support format call so I get the folowing error.
Use f-string instead of 'format' call for the functions below.
def write_xlsx_response(self, queryset)...
0
votes
0
answers
30
views
how to format with double quotes using f-format in python? [duplicate]
I want to enclose each element of a list with double quotes instead of single?
With f-string I'm not able to get double quotes and when I try solutions from the internet it's applying double quotes to ...
-1
votes
1
answer
48
views
Get error when try to put string-funcs in f-string [duplicate]
a = 'guindo , barwos, zasport'
a
guindo , barwos, zasport
But when I write
print(f'find is {a.find('a')}')
I get error
SyntaxError: f-string: unmatched '('
Why? Can someone please write right ...
1
vote
1
answer
991
views
python 3.12 f-string inelegance
MY_WIDTH = 80
MY_CONSTRUCTED_HDR = f"this is a hdr of length {MY_WIDTH}"
print(MY_CONSTRUCTED_HDR)
this is a hdr of length 80 # YES, but NOT what I need -- see below
I want something like ...
0
votes
1
answer
106
views
Why does comparison between empty ndarrays and empty lists behave differently if done inside an f-string? [closed]
I was messing around a bit with empty ndarrays and uncovered some unexpected behavior. Minimal working example:
import numpy as np
print(f"{np.empty(0)} :: {type(np.empty(0))}")
print(f&...
0
votes
1
answer
58
views
F-string are putting the "" inside a {} [closed]
My Code:
videos = []
for keys in data:
videos.append({f"'path: 'videos/{filename}.mp4', 'description': '{filename}'"},)
The problem:
problem
As you can see the f-string is putting the &...
0
votes
1
answer
97
views
How to convert Python2 string with formatting into the new f string used in python3
I am working on converting some Python 2.7 code to reflect a more Python 3.10 method and came across this scenario. A string variable is holding the formatting and then later on variables are added to ...
1
vote
2
answers
186
views
Is there an efficient way to format Decimal?
It is nice, easy and fast to use format-strings in python. So I never considered the performance penalty of this operation. Some time ago I switched my program from float data type to Decimal to ...
0
votes
2
answers
76
views
Python file wont write blank new line
I'm making these report files and am trying to append a blank line in between each cycle of my loop, just to help with readability.
Usually, I can just open the file and f.write('\n') to do this - for ...
1
vote
2
answers
226
views
Manage None values in F String
I am creating a string using f string and need to avoid fields which are None.
I am currently using below code
def output(self) -> str:
data = ''
data += 'Books: [\n'
for ...
0
votes
1
answer
37
views
Python: save output file with the logged-in username appended to the file name
I have a python program that creates an output file. That all works correctly.
However, I'd now like to save the python output file with a "_username" appended to the filename.
I have ...
0
votes
1
answer
293
views
not sure why I get a syntax error when trying to run a SQL UPDATE query using f strings [duplicate]
I am trying to run a basic SQL query to UPDATE the value for schoolNum from a database called bartonHill, using f strings to put the values in
import sqlite3
name = [input('enter your firstname: ')]
...
1
vote
1
answer
114
views
Iterating through a list of countries to pull data from Datastream
I am pulling data from Datastream for a project. I have a list of 40 countries for which I want their bond issuance information.
The query is as follows:
All1 = rd.discovery.search(
view = rd....
0
votes
1
answer
88
views
does the f-string convert an integer to a string?
Hello I was practicing using loops and I saw that while using concatenation I have to convert int's to strings, but then I saw that if I use a f-string I dont need convert it to an int.
Here is the ...
-1
votes
3
answers
255
views
Automatically turn a string into a formatted string? (Python)
I'd like to program an alternate print() function, that automatically turns the inputted string into a formatted one, with correct formatting for variables.
So why doesn't this work?
Test = 'Hello!'
...
0
votes
1
answer
149
views
Variable assignment in an f-string [duplicate]
Question question regarding f-strings and expressions in Python 3.
The Python documentation states clearly that:
Formatted string literals (also called f-strings for short) let you
include the value ...