Number to string with leading (left padded) zeros in Julialang - string

It seems as an easy question, but I cannot find the answer anywhere. If I have an integer variable, how can I transform it to a string with leading zeros?
I want something as the code below:
n = 4
string_size = 3
println(fleading(n, string_size))
# result should be "004"
Where fleading would be something like the function to transform the number to string with leading zeros. The analogous way in python is str(4).zfill(3) which gives 004 as result.

You're looking for the lpad() (for left pad) function:
julia> lpad(4,3,"0")
"004"
Note the last argument must be a string.
From the documentation:
lpad(string, n, "p")
Make a string at least n columns wide when printed, by padding on the left
with copies of p.

For Julia 1.0 the syntax is:
lpad(s, n::Integer, p::Union{AbstractChar,AbstractString}=' ')
The example is therefore:
julia> lpad(4, 3, '0')
004

There is also #printf("%03i",4) using Printf.#printf

Related

Shifting string using Julia

This challenge in Hackerrank is to shift the string using Julia(programming language( and return the string. I have a function that takes in 3 arguments.
shiftStrings("string", leftShifts, rightShifts)
Left Shift: A single circular rotation of the string in which the first character becomes the last character and all other characters are shifted one index to the left. For example, abcde becomes bcdea after 1 left shift and cdeab after 2 left shifts.
Right Shift: A single circular rotation of the string in which the last character becomes the first character and all other characters are shifted to the right. For example, abcde becomes eabcd after 1 right shift and deabc after 2 right shifts.
I passed only 3 out of 13 test cases. Here is my solution. Please let me know the better solution.
Please refer this, they have done by python
How to shift characters in a string? - Hackerrank challenge
If you take a look at the question you linked they already had an answer to that in python.
def getShiftedString(s, leftShifts, rightShifts):
i = (leftShifts - rightShifts) % len(s)
return s[i:] + s[:i]
If you want to shift a string to the right and then to the left you just need the difference of both. I.e. if you shift 3 to the right and 3 to the left it's like you didn't change anything. "abcde" 3 to the left -> "deabc" 3 to the right -> "abcde".
Therefore, this leads to:
function shiftStrings(str, l, r)
i = mod(l - r, length(str))
str[i+1:end] * str[1:i]
end
Note:
i is the total amount of leftshifts (you take the modulo of leftshifts minus the rightshifts)
Python indexing starts from 0, whereas Julia indexing starts from 1, while modulo returns a 0 if l-r==0, that's why [i+1:end] and [1:i]
If you have Utf8 encoding then you can formulate it like this:
function shiftStrings(str, l, r)
i = mod(l - r, length(str))
indices = collect(eachindex(str))
str[indices[i+1]:end] * str[1:indices[i]]
end
Utf8 characters do not correspond to 1 byte per character, that's why the character indices are different that the String indices. (String indexing starts at every new byte, but some characters like the German "รถ" need more than 1 byte)
function getShiftedString(s, leftShifts, rightShifts)
len=length(s)
lr=mod(leftShifts,len)
rr=len-mod(rightShifts,len)
ls1=SubString(s,lr+1,length(s))
ls2=SubString(s,1,lr)
ls=ls1*ls2
rs1=SubString(ls,rr+1,length(s))
rs2=SubString(ls,1,rr)
rs=rs1*rs2
end

How to add Leading zero/zeros in azure logic app for the variable?

Ideally, there should be 6 digits in a variable called 'subject'
"how to fill the 0 if not 6digit in the subject variable?"
example *subject = 387592(continue the process)
*subject = 35885(add zero to make 6digit = 035885)
*subject = 7161( add zeros 007161)
python zfill(6) helps to solve this kind of issues
An old school string parsing approach should do the trick:
substring(concat('000000',variables('IntString4')),sub(length(concat('000000',variables('IntString4'))),6),6)
Here's the breakdown:
Concat the existing string with leading zeros
concat('000000',variables('IntString4')
Measure the length of the string and subtract the desired length to calculate the starting index of the eventual substring:
sub(length(concat('000000',variables('IntString4'))),6)
Use substring to capture the last 6 characters:
substring(#1,#2,6)
You could make this a bit more readable and dynamic with variables, but same logic applies.
Have you tried using the "formatNumber" function?
For example, in your case
formatNumber('35885', '000000') -> Result "035885"
formatNumber('7161', '000000') -> Result "007161"
https://learn.microsoft.com/es-es/azure/logic-apps/workflow-definition-language-functions-reference#formatNumber

Is there a built-in in Python 3 that checks whether a character is a "basic" algebraic symbol?

I know the string methods str.isdigit, str.isdecimal and str.isnumeric.
I'm looking for a built-in method that checks if a character is algebraic, meaning that it can be found in a declaration of a decimal number.
The above mentioned methods return False for '-1' and '1.0'.
I can use isdigit to retrieve a positive integer from a string:
string = 'number=123'
number = ''.join([d for d in string if d.isdigit()]) # returns '123'
But that doesn't work for negative integers or floats.
Imagine a method called isnumber that works like this:
def isnumber(s):
for c in s:
if c not in list('.+-0123456789'):
return False
return True
string1 = 'number=-1'
string2 = 'number=0.1'
number1 = ''.join([d for d in string1 if d.isnumber()]) # returns '-1'
number2 = ''.join([d for d in string2 if d.isnumber()]) # returns '0.1'
The idea is to test against a set of "basic" algebraic characters. The string does not have to contain a valid Python number. It could also be an IP address like 255.255.0.1.
.
Does a handy built-in that works approximately like that exist?
If not, why not? It would be much more efficient than a python function and very useful. I've seen alot of examples on stackoverflow that use str.isdigit() to retrieve a positive integer from a string. Is there a reason why there isn't a built-in like that, although there are three different methods that do almost the same thing?
No such function exists. There are a bunch of odd characters that can be part of number literals in Python, such as o, x and b in the prefix of integers of non-decimal bases, and e to introduce the exponential part of a float. I think those plus the hex digits (0-9 and A-F) and sign characters and the decimal point are all you need.
You can put together a string with the right character yourself and test against it:
from string import hex_digits
num_literal_chars = hex_digits + "oxOX.+-"
That will get a bunch of garbage though if you use it to test against mixed text and numbers:
string1 = "foo. bar. 0xDEADBEEF 10.0.0.1"
print("".join(c for c in string1 if c in num_literal_chars))
# prints "foo.ba.0xDEADBEEF10.0.0.1"
The fact that it gives you a bunch of junk is probably why no builtin function exists to do this. If you want to match a certain kind of number out of a string, write an appropriate regular expression to match that specific kind of number. Don't try to do it character-by-character, or try to match all the different kinds of Python numbers.

Convert a string into an integer of its ascii values

I am trying to write a function that takes a string txt and returns an int of that string's character's ascii numbers. It also takes a second argument, n, that is an int that specified the number of digits that each character should translate to. The default value of n is 3. n is always > 3 and the string input is always non-empty.
Example outputs:
string_to_number('fff')
102102102
string_to_number('ABBA', n = 4)
65006600660065
My current strategy is to split txt into its characters by converting it into a list. Then, I convert the characters into their ord values and append this to a new list. I then try to combine the elements in this new list into a number (e.g. I would go from ['102', '102', '102'] to ['102102102']. Then I try to convert the first element of this list (aka the only element), into an integer. My current code looks like this:
def string_to_number(txt, n=3):
characters = list(txt)
ord_values = []
for character in characters:
ord_values.append(ord(character))
joined_ord_values = ''.join(ord_values)
final_number = int(joined_ord_values[0])
return final_number
The issue is that I get a Type Error. I can write code that successfully returns the integer of a single-character string, however when it comes to ones that contain more than one character, I can't because of this type error. Is there any way of fixing this. Thank you, and apologies if this is quite long.
Try this:
def string_to_number(text, n=3):
return int(''.join('{:0>{}}'.format(ord(c), n) for c in text))
print(string_to_number('fff'))
print(string_to_number('ABBA', n=4))
Output:
102102102
65006600660065
Edit: without list comprehension, as OP asked in the comment
def string_to_number(text, n=3):
l = []
for c in text:
l.append('{:0>{}}'.format(ord(c), n))
return int(''.join(l))
Useful link(s):
string formatting in python: contains pretty much everything you need to know about string formatting in python
The join method expects an array of strings, so you'll need to convert your ASCII codes into strings. This almost gets it done:
ord_values.append(str(ord(character)))
except that it doesn't respect your number-of-digits requirement.

Converting between a number to a string without num2str

For example, input is a=5678. How do you make b='5678'? (b is a String).
Not allowed to use str2num or any casting.
Is it possible to use log10? (I know how to do the reverse action).
[This is how I did the opposite (from string to num):
s = input('Enter a number: ','s');
x = sum(10.^(length(s-'0')-1:-1:0).*(s-'0'));
This looks like homework, so first here are some hints:
log10 may be useful to determine the number of digits.
mod can help to obtain each digit.
From your code for the reverse action: using successive powers of 10, as well as +'0' / -'0' to convert between digits and ASCII codes, may also be of help here.
And here's a possible approach using these hints (hover the mouse to find out):
b = char(mod(floor(a./10.^((ceil(log10(a))-1):-1:0)),10) + '0'):

Resources