This question already has answers here:
How do I put a variable’s value inside a string (interpolate it into the string)?
(9 answers)
Closed 6 years ago.
I have make a set of names in this form: 's1', 's2', ..., 's100'. I thought I can do that easily via looping:
for i in range(100):
print ('s'.format(i+1))
format here does not append the numbers. I only get ss..ss without the numbers being concatenated in single quote. I know how to do this in Java but I am not that much expert in Python. Thank you
You need to have a placeholder in the format string:
Perform a string formatting operation. The string on which this method
is called can contain literal text or replacement fields delimited by
braces {}. Each replacement field contains either the numeric index of
a positional argument, or the name of a keyword argument.
for i in range(100):
print ('s{0}'.format(i+1))
If you use 3.6, then you can take advantage of the new 'Literal String Interpolation', and do the following:
for i in range(100):
print(f's{i + 1}')
For more details on this feature, check out PEP 498 -- Literal String Interpolation
Related
This question already has answers here:
String concatenation without '+' operator
(6 answers)
Closed 3 years ago.
Though it might seem a very trivial question, I still want to know the principle behind it. When we write multiple strings together without any comma,python concatenates them. I was under the impression that it will throw some error. Below is a sample output:
print('hello''world')
# This will output helloworld
Even if I write those multiple strings in the python REPL, the output will be the concatenated form of the strings. Can anyone please explain the logic behind this operation ?
See https://docs.python.org/3.8/reference/lexical_analysis.html#string-literal-concatenation.
Multiple adjacent string or bytes literals (delimited by whitespace), possibly using different quoting conventions, are allowed, and their meaning is the same as their concatenation.
Thus, "hello" 'world' is equivalent to "helloworld". This feature can be used to reduce the number of backslashes needed, to split long strings conveniently across long lines, or even to add comments to parts of strings
This question already has answers here:
How do I put a variable’s value inside a string (interpolate it into the string)?
(9 answers)
Closed 3 years ago.
I'm coding a little game and I want a score system. I have two variables that I want to display as "The current score is: X/X" but its not including the variables
I've tried putting it in 'quotes' put it didn't work
U = 2
L = 3
print("Current score: U/L")
I want it to be "Current score: 2/3"
print(f"Current score: {U}/{L}")
Strings enclosed with simple quotes or double-quotes imply that all characters in it are just literal text - they are not interpreted as variables.
From Python 3.6, the prefix f for the quotes delimiting the string denotes an special literal which can include Python expressions inside - including variables. Still, to separate these variables from plain text (and avoid unpredictable substitutions), these expressions have to be further delimited by { }, inside the string.
Prior to Python 3.6, one would have to do it in two separate steps: create a plain string with special markers were the variables contents would be inserted, and then call the .format method on the string. (or, there is an older method using the % operator instead). Fully documenting these other methods would be long - but a short form would require one to write:
print("Current score: {}/{}".format(U, L))
This question already has answers here:
Slicing strings in str.format
(6 answers)
Closed 6 years ago.
How can I do variable string slicing inside string.format like this.
"{0[:2]} Some text {0[2:4]} some text".format("123456")
Result I want result like this.
12 Some text 34 some text
You can't. Best you can do is limit how many characters of a string are printed (roughly equivalent to specifying a slice end), but you can't specify arbitrary start or end indices.
Save the data to a named variable and pass the slices to the format method, it's more readable, more intuitive, and easier for the parser to identify errors when they occur:
mystr = "123456"
"{} Some text {} some text".format(mystr[:2], mystr[2:4])
You could move some of the work from that to the format string if you really wanted to, but it's not a huge improvement (and in fact, involves larger temporaries when a slice ends up being needed anyway):
"{:.2s} Some text {:.2s} some text".format(mystr, mystr[2:])
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 6 years ago.
again :)
I found this bit of code
col_width=[13,11]
header=['First Name','Last Name']
format_specs = ["{{:{}}}".format(col_width[i]) for i in range(len(col_width))]
lheader=[format_specs[i].format(self.__header[i]) for i in range(nb_columns)]
How Python evaluate this statement? Why we use three { when we have one element to format in every iteration?
when you do {{}}, python skips the replacement of {} and makes it the part of string. Below is the sample example to explain this:
>>> '{{}}'.format(3) # with two '{{}}'
'{}' # nothing added to the string, instead made inner `{}` as the part of string
>>> '{{{}}}'.format(3) # with three '{{{}}}'
'{3}' # replaced third one with the number
Similarly, your expression is evaluating as:
>>> '{{:{}}}'.format(3)
'{:3}' # during creation of "format_specs"
For details, refer: Format String Syntax document.
This question already has answers here:
String concatenation without '+' operator
(6 answers)
Closed 7 years ago.
I just discovered what I thought was a typo but Python accepts it.
foo = {'a': 'b'}
foo.get('a'"")
returns 'b'. Where in Python is 'a'"" defined as a valid parameter to a function?
Python concatenates all consecutive strings. It doesn't matter if that's in a function or elsewhere.
See the String literal concatenation section of the reference documentation:
Multiple adjacent string literals (delimited by whitespace), possibly using different quoting conventions, are allowed, and their meaning is the same as their concatenation.
This is done at the parsel level; the final bytecode stores just the one string object. See What is under the hood of x = 'y' 'z' in Python?
The feature was copied from C. From a (failed) proposal to remove the feature:
Many Python parsing rules are intentionally compatible with C. [...] In C, implicit concatenation is the only way to join strings without using a (run-time) function call to store into a variable.
The feature is very useful when producing long strings:
long_value = (
'The quick brown fox jumped over the lazy fox and kept '
'the string within the 80 character boundary.'
)