Please explain '%' usage in python [duplicate] - python

This question already has answers here:
What does %s mean in a Python format string?
(7 answers)
String formatting in Python [duplicate]
(14 answers)
String formatting: % vs. .format vs. f-string literal
(16 answers)
Closed 4 years ago.
I'm learning multithreading in python and I was reading through this answer. I understand most of the code however there is this one line which I simply don't understand and I don't know how to search for it on Google as the '%' sign keeps returning modulo.
req.headers['Range'] = 'bytes=%s-%s' % (start, start+chunk_size)
I thought that req.headers['Range'] would retrieve some 'range' element from an array however here they are assigning it a value of 'bytes=%s-%s' % (start, start+chunk_size). I really just don't understand what is going on in this line. Things like 'bytes=%s-%s' I am assuming is some sort of python syntax which I am unaware of. If you could explain each term in this line that would be very much appreciated.

In python there are multiple ways to format strings. using %s inside a string and then a % after the string followed by a tuple (or a single value), allows you to create a new string:
x = 5
y = 8
'my favourite number is %s, but I hate the number %s' % (x, y)
results in:
'my favourite number is 5, but I hate the number 8'
I think they call it C-type string formatting. For more information, you can check out this page.
In my opinion, it is easier to format string using f'strings, or .format(). Check out this page too

Related

Python triple quotes and percentage (%) syntax [duplicate]

This question already has answers here:
What does the percentage sign mean in Python
(8 answers)
What is the difference between single, double, and triple quotes in Python? [duplicate]
(1 answer)
Closed 2 years ago.
I need to write a script to send an email using sendmail. The code that I'm looking at was found here: http://effbot.org/pyfaq/how-do-i-send-mail-from-a-python-script.htm
I am trying to figure out what this syntax means:
FROM = "sender#domain.ca"
TO = ["recipient#domain.ca"]
SUBJECT = "Hello!"
TEXT = "This message was sent via sendmail."
# Prepare actual message
message = """\
From: %s
To: %s
Subject: %s
%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
From what I can gather the triple quote is used when you need to create a very long string with keywords so that python doesn't try to interpret them. However the percentage used after the triple quote is what intrigues me. Is it some sort of concatenate operator like ampersand?
I'm almost certain this is a duplicate of something but if it's not, what you're looking at is a formatted string. Triple quote is a valid way to form a string in python.
see https://www.learnpython.org/en/String_Formatting

What does '%%' mean in python? [duplicate]

This question already has answers here:
How can I selectively escape percent (%) in Python strings?
(6 answers)
What is %% for in Python? [duplicate]
(1 answer)
Closed 4 years ago.
I came across a problem when I was learning python.
print('test%d, %.2f%%' % (1,1.4))
however, it has an error.
ValueError: incomplete format
But if I execute like this:
print('test%d, %.2f%%' % (1,1.4))
test1, 1.40%
It works and prints the '%'. But I don't know why? Can someone help me? Thanks.
Since % is used as a special character in (old C-style) format strings, you have to use %% to print a literal percent sign.
You need to look into c-style string formatting. %% is a reference to this series of string formatting commands.
The following page:
https://docs.python.org/3.4/library/string.html
has a "String formatting mini-language" section that answers your question in meticulous detail.

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'

How to add an integer into this Regex in Python without hard coding the integer? [duplicate]

This question already has answers here:
How to use a variable inside a regular expression?
(12 answers)
Closed 5 years ago.
I want to eventually be able to increment an integer within my Regex, but the braces are preventing me from doing so.
So far I have:
start = 6
m = re.search(r"(.{{n},}).*?\1".format(n=start), s)
return m.group(1)
However, I get `ValueError: Single '}' encountered in format string
I am using Python 2.7.
What about using a different method of string formatting:
m = re.search(r"({.%s,}).*?\1" % start, s)

%% in sec2time() Python [duplicate]

This question already has answers here:
How can I selectively escape percent (%) in Python strings?
(6 answers)
Closed 6 years ago.
In the sec2time() Python function provided by Lee he uses a syntax I'm struggling to understand:
pattern = '%%02d:%%02d:%%0%d.%df' % (n_msec+3, n_msec)
What is the %%here and how does it affect the outcome?
The % in that string introduces replaceable parts as at the end %d.%df. If you want a % in the output you have to do something special, in this case use %%
After these substitustions the resulting pattern will look like:
'%02d:%02d:%0123.120f'
which, among other things an be used for further substitution.
In the documentation, at the bottem of the second table in that section, it states:
'%' No argument is converted, results in a '%' character in the result.

Categories