Let's say I have 2 variables dir_name = mydir
and file_name = file1
, each to be used in formatted strings. There're a few ways to insert a /
in a string with those 2 variables.
dir_name = mydir/
;file_name = file1
dir_name = /mydir
;file_name = /file1
dir_name = mydir
;file_name = file1
With Python, there are 3 common ways to create format strings: concatenation, f strings and .format()
. When using concatenation, options 1 and 2 makes it so that we don't need to concat an extra /
which may be more readable. With f strings and .format()
though, I find not having the /
in the names makes it slightly more readable with something like f"{dir_name}/{file_name}"
or "{}/{}".format(dir_name, file_name)
which clearly has a separating /
in it instead of a bunch of variables squashed together.
Between options 1 and 2, option 1 makes it clear which variable is a directory and which is a file. Option 2 though, feels a bit more uniform to me.
I know this is a small issue but I've found it to have a slight impact on code readability for me, mainly in Python with a lot of directories.
Is there a standard way to insert the /
in directory and file name strings?
os.path.join()
(or similar in other languages) so it doesn't matter. – user949300 Apr 23 '21 at 02:58join()
method is not applicable (is an URL, or Unix path on Windows). It is better then to rely on typesafe representation of path as a list of segments, where each segment if forbidden to have delimiters. There are libraries for that. – Basilevs Apr 23 '21 at 05:57/
operator, so that the separator doesn't have be stored anywhere and no string formatting is necessary. – Kilian Foth Apr 23 '21 at 06:04urlparse.urljoin
exists for that purpose. 2) At least in Python,posixpath
andntpath
exist if you're dealing with a specific filesystem. – Philip Kendall Apr 23 '21 at 10:36