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:])
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 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
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 formatting: % vs. .format vs. f-string literal
(16 answers)
Closed 8 years ago.
I find it takes quite a bit of focus, time an effort to format a string with the syntax I'm currently using:
myList=['one','two','three']
myString='The number %s is larger than %s but smaller than %s.'%(myList[1],myList[0],myList[2])
Result:
"The number two is larger than one but smaller than three"
Strange but every time I reach % keyboard key followed by s I feel kind of interrupted...
I wonder if there is alternative way of achieving a similar string formatting. Please post some examples.
You may be looking for str.format, the new, preferred way to perform string formatting operations:
>>> myList=['one','two','three']
>>> 'The number {1} is larger than {0} but smaller than {2}.'.format(*myList)
'The number two is larger than one but smaller than three.'
>>>
The main advantage of this method is that, instead of doing (myList[1],myList[0],myList[2]), you can simply unpack myList by doing *myList. Then, by numbering the format fields, you can put the substrings in the order you want.
Note too that numbering the format fields is unnecessary if myList is already in order:
>>> myList=['two','one','three']
>>> 'The number {} is larger than {} but smaller than {}.'.format(*myList)
'The number two is larger than one but smaller than three.'
>>>
This question already has answers here:
MongoDB Regex Search on Integer Value
(2 answers)
Closed 8 years ago.
Is it possible to use regex on a number instead of a string?
For example: I have a field in a mongodb that contains the numeric value 1234567 (not stored as a string for sorting purposes etc.).
Now I want to use regex to find parts of this number, i.e. 456.
On a database-field that contains a string "1234567" this is easy: I just pass re.compile("456") to my database query. However re.compile(456) gets me the following:
TypeError: first argument must be string or compiled pattern
Any hints on how to accomplish this? Storing my numbers as strings is not really an option, since I would lose lots of other possibilities (like gt/lt, sorting etc.).
Update:
Also, I'm passing the regex right into the db-query to filter results, so I cannot pull up an individual field, convert it's content to a string and then use the regex on it.
You can convert a number to a string using the built-in str function:
str(456)
Marking as duplicate: MongoDB Regex Search on Integer Value
db.test.find({ $where: "/^123.*/.test(this.example)" })
{ "_id" : ObjectId("4bfc3187fec861325f34b132"), "example" : 1234 }
This isn't possible with MongoDB. Depending on your application, you might be able to store these numbers as string-typed values instead of numbers. In Python:
db.collection.insert({"my_number": "12345678"})
For phone numbers or zipcodes where arithmetic operations like $inc don't make sense, but where you want to use a regex to search your data, this could make sense.
An alternate approach could be to store each number both as a string and as a number:
db.collection.insert({"s": "12345678", "n": 12345678})