This question already has answers here:
How to remove leading and trailing zeros in a string? Python
(7 answers)
Closed last year.
I'm having issues skipping or trimming the first two numbers in a provided argument.
As an example I am passing the value of "00123456" to 'id'. I want the request.args.get against 123456 instead 00123456. is there a function I can use to drop off the zero's. Also relatively new to the python world so please advise if I need to provide more info.
#main.route('/test')
def test():
"""
Test route for validating number
example - /test?id=00123456
"""
# Get number passed in id argument
varNum = request.args.get('id')
You can convert the "00123456" to an int and it will remove all the zeros at the start of the string.
print(int("00123456"))
output:
123456
Edit:
Use this only if you want to remove any zeros at the start of the number, if you want to remove the first two chars use string slicing.
Also, use this only if u know for sure that the str will only contain numbers.
You can use string slicing, if you know that there are always two zeroes:
varNum = request.args.get('id')[2:]
Alternatively, you can use .lstrip(), if you don't know how many leading zeroes there are in advance:
varNum = request.args.get('id').lstrip('0')
Related
This question already has answers here:
How to get the size of a string in Python?
(6 answers)
Closed 1 year ago.
we have just begun our unit on recursion, and I had a question regarding non-recursive functions and strings
I understand that strings are inherently recursive, as each character within a string has its own positive or negative index value, but I am a little unclear on how to create this function.
EDIT: Please disregard above text
What I meant to say:
I understand that a sequence is recursive in nature, that a string is a character followed by another string, just as a list is an element followed by another list.
Imagine we had a function called:
def flipside(s)
And when we input a string into our s parameter of the function, for example, the string:
'homework'
It takes the first half of the string (s) and moves it to the back while taking the second half of the string moving it the front, effectively generating the output:
'workhome'
I guess what I am having an issue with, is regarding string operations. If I do not know the length of s because it can take on any value due to it being a parameter, how do I create a non-recursive program to take 1//2 of s and move that half of the string to the back while simultaneously pushing the second half forward.
I have only gone so far as to set my base case:
def flipside(s):
if s == (''):
return 0
else:
fliprest =
return fliprest
Thank you, I would appreciate any information on the thought process behind your logic, or any feedback regarding any bad habits that I may be developing with how I have started off my code.
You can use slicing
def flipside(s):
return s[len(s)//2:] + s[:len(s)//2]
>>> flipside('homework')
'workhome'
I want to have a string where I can format it with an integer so that it:
Adds a sign in front of the integer (+ for positive ints, - for negative ints)
Surround the signed int with parentheses (i.e. with ())
Left align the int with parentheses on the left, adding if necessary spaces to the end.
I know how to do these steps separately, but I haven't been able to combine them into a single string.
1 and 2 would be accomplished with for example '({:+d})'.format(3), this would result in (+3).
3 is done for an arbitrary string with '{:<5}'.format(3), this would result in 3 (4 trailing spaces).
My goal is to have a single string where I can call .format on only once, so
format_string.format(3)
would result in
(+3)
with one trailing space to make the string length 5.
Is this possible?
I've tried ({{:+d}:<5}) but this doesn't work as it thinks {:+d} is the field name to format with <5, which is obviously not the case.
I've also looked into f-strings, but these are not suitable for my use case as I call .format on the format string later than when it's created.
Any help would be most welcome!
Solution with one call for format:
def special_format_int(n, SPACES=5):
return '({:+d})'.format(n).ljust(SPACES)
Personally, I have the following string "E2017010000000601". This character E is for control, after comes the year, then the month and in the last positions comes a user code with a maximum of 7 positions. I would like to know how can I in Python remove those 0 from the middle of the string that are unnecessary.
For example, in the string "E2018090001002202", I do not need these 3 zeros between 9 and 1.
Already in the string "E2017010000000601", I do not need those 7 zeros between 1 and 6 ..
I have over 1000 files with this type of string, and renaming it one by one is tricky. I know that in Python I can rename this huge amount of files, but I did some code and I'm not able to mount the way I explained ... Any help?
This is basic string slicing as long as you are sure the structure is identical for each string.
You can use something like:
original_string = "E2017010000000601"
cut_string = str(int(original_string[7:]))
This should work because first you remove the first 7 values, the control char, year and month.
Then you turn to integer which removes all the zeroes at the front, then back to string.
Basically the same answer as Alexis, but since I can't comment yet, in a separate answer: since you want to keep the "EYYYYMM" part of the string, the code would be:
>>>original_string = 'E2017010000000601'
>>>cut_string= original_string[:7] + str(int(original_string[7:]))
>>>cut_string
'E201701601'
A quick explanation: we know what the first seven characters of the string will be, and we want to keep those in the string. Then we add the rest of the string, turned into an integer and back into a string, so that all unnecessary zeroes in front are removed.
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})
I've been searching on this but am coming up a little short on exactly how to do specifically what i am trying to do.. I want to concatentate a string (I guess it would be a string in this case as it has a variable and string) such as below, where I need to use a variable consisting of a string to call a listname that has an index (from another variable).. I simplified my code below to just show the relevant parts its part of a macro that is replacing values:
toreplacetype = 'type'
toreplace_indx = 5
replacement_string = 'list'+toreplacetype[toreplace_indx]
so... I am trying to make the string on the last line equal to the actual variable name:
replacement_string = listtype[5]
Any advice on how to do this is appreciated
EDIT:
To explain further, this is for a macro that is sort of a template system where I am indicating things in a python script that I want to replace with specific values so I am using regex to do this. So, when I match something, I want to be able to replace it from a specific value within a list, but, for example, in the template I have {{type}}, so I extract this, but then I need to manipulate it as above so that I can use the extracted value "type" to call a specific value from within a list (such as from a list called "listtype") (there is more than 1 list so I need to find the one called "listtype" so I just want to concatenate as above to get this, based on the value I extracted using regex
This is not recommended. Use a dict instead.
vars['list%s' % toreplacetype][5] = ...
Hrm...
globals()['list%s'% toreplacetype][toreplace_indx]
replacement_string = 'list'+toreplacetype+'['+str(toreplace_indx)+']'
will yield listtype[5] when you print it.
You need to basically break it into 5 parts: 1 string variable, 3 strings and an int casted to a string.
I think this is what you are asking?