Using format instead of f string [duplicate] - python

This question already has answers here:
String formatting: % vs. .format vs. f-string literal
(16 answers)
String formatting in Python 3
(5 answers)
Closed 2 years ago.
I have python 3.7.4 and it has f string support. But the server I am porting my data has python < 3.6 and so does not support f string. The following code works fine in local machine:
directory_root = 'dataset_test/'
root_dir = listdir(directory_root)
for animal_folder in root_dir:
animal_folder_list = listdir(f"{directory_root}/{animal_folder}")
But this code fails in server as it does not support f string. How could I rewrite it using format ?

You can write it like this:
listdir("{directory_root}/{animal_folder}".format(directory_root=directory_root, animal_folder=animal_folder))
Or
listdir("{}/{}".format(directory_root, animal_folder))

You can simply use string formatting like following
"Your string {0} {1}...{}".format(variable1, variable2, variable)

The correct way, that works in every environment, not only on your local linux box would be:
animal_folder_list = listdir(os.path.join( directory_root, animal_folder))
When you explicitly specify folder separator (/), it will break on Win-boxes or in other hostile environments. os.path.join() comes to the rescue =)

Related

Is it possible run a string in Python [duplicate]

This question already has answers here:
How do I execute a string containing Python code in Python?
(14 answers)
Closed 1 year ago.
Is it possible to run a String text?
Example:
str = "print(2+4)"
Something(str)
Output:
6
Basically turning a string into code, and then running it.
Use exec as it can dynamically execute code of python programs.
strr = "print(2+4)"
exec(strr)
>> 6
I will not recommend you to use exec because:
When you give your users the liberty to execute any piece of code with the Python exec() function, you give them a way to bend the rules.
What if you have access to the os module in your session and they borrow a command from that to run? Say you have imported os in your code.
Sure is, looks like your "Something" should be exec.
str = "print(2+4)"
exec(str)
Check out this previous question for more info:
How do I execute a string containing Python code in Python?

How to write file locations as string in python [duplicate]

This question already has answers here:
How should I write a Windows path in a Python string literal?
(5 answers)
Closed 2 years ago.
I cant seem to write something like : "C:\Users\alon4\Desktop\Learning Material\Odyssey\Lab a2\Magnetism\data"
As a string to print or otherwise, i think its something to do with the slashes
There can be 3 ways :
1) Either use r (raw strings) before the actual string :
For example : r"C:\Users\alon4\Desktop\Learning Material\Odyssey\Lab a2\Magnetism\data"
2) Or use // like:
For example : "C:\\Users\\alon4\\Desktop\\Learning Material\\Odyssey\\Lab a2\\Magnetism\data"
3) Use slashes: "C:/Users/alon4/Desktop/Learning Material/Odyssey/Lab a2/Magnetism/data"
(As suggested by Óscar López)

Trouble using python re with the format option [duplicate]

This question already has answers here:
How do I escape curly-brace ({}) characters in a string while using .format (or an f-string)?
(23 answers)
Closed 2 years ago.
I have multiple files of the format myfilexyz-200407171758.tar.gz
(myfilexyz)-(200407171758).tar.gz
Group1 is a variable.
Group2 can be of 12 to 14 digits.
Using variable substitution, I can get this working
r = re.compile('(%s)-(\d){12,13}.tar.gz' %myvar)
But if I were to try the newer format method, I get into trouble
r = re.compile('({})-(\d){12,14}.tar.gz'.format(myvar))
key '12,14' has no corresponding arguments
Obviously the {12,14} is messing up format. Is there a way around this problem and still use the format method for substitution?
From documentation,
If you need to include a bracing character in the literal text, it can be escaped by doubling:
{{ and }}.
Use
'({})-(\d){{12,14}}.tar.gz'.format(myvar)
Also, format is older way of doing it. Use f-string
f'({myvar})-(\d){{12,14}}.tar.gz'
Why not concatenate directly?
myvar + '-(\d){{12,14}}.tar.gz'

Opening files with the name of a variable [duplicate]

This question already has answers here:
String formatting: % vs. .format vs. f-string literal
(16 answers)
Closed 4 years ago.
I am using a Markov chain. When the chain arrives at a particular state, two files (a .png and an .mp3) need to open.
s is the current state of the chain, an integer from 1-59.
I can't seem to find how to open the file with the same number as 's'.
I'm sure it has something to do with %str formatting, but I can't seem to implement it.
img = Image.open('/.../.../s.png')
img.show()
You should use the following line in your code:
img = Image.open('/.../.../{0}.png'.format(s))
You can format a string using a variable like this
>>> s = 10
>>> '/path/to/file/{}.png'.format(s)
'/path/to/file/10.png'

Python adds x0 to integers [duplicate]

This question already has an answer here:
Python 3.4.1 script syntax error, arcpy & [duplicate]
(1 answer)
Closed 7 years ago.
I am very new to Python and am getting this small problem. I am using Python 3.3
There is a variable I declared in my code
file_name = "resource\email\ham\6.txt"
However, when I look for the variable, it appends additional numbers
>>file_name
'resource\\email\\ham\x06.txt'
Is there a reason why it behaves as so? If not, how do I remove those additional characters? Also, why are they there?
Use r raw string:
file_name = r"resource\email\ham\6.txt"
Double \:
file_name = "resource\\email\\ham\\6.txt"
Or /:
file_name = "resource/email/ham/6.txt"
\ has a special meaning in python, it is used to escape characters.

Categories