Python how to remove the first set of a character in a string? - python-3.x

My variable x has a value of "000032403" and I want to remove the first set of zeros but I want to keep the other! How I gonna do that?
Note: Please give me any suggestions without knowing the amount of zeros in the beginning, because in my program this value is obtained from the user.

You can use the lstrip() function of the string class like this
>>> x = "000032403"
>>> x.lstrip("0")
"32403"
This will "return a copy of the string with leading characters removed".
Here's a link to the docs

Related

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

re.sub replacing string using original sub-string

I have a text file. I would like to remove all decimal points and their trailing numbers, unless text is preceding.
e.g 12.29,14.6,8967.334 should be replaced with 12,14,8967
e.g happypants2.3#email.com should not be modified.
My code is:
import re
txt1 = "9.9,8.8,22.2,88.7,morris1.43#email.com,chat22.3#email.com,123.6,6.54"
txt1 = re.sub(r',\d+[.]\d+', r'\d+',txt1)
print(txt1)
unless there is an easier way of completing this, how do I modify r'\d+' so it just returns the number without a decimal place?
You need to make use of groups in your regex. You put the digits before the '.' into parentheses, and then you can use '\1' to refer to them later:
txt1 = re.sub(r',(\d+)[.]\d+', r',\1',txt1)
Note that in your attempted replacement code you forgot to replace the comma, so your numbers would have been glommed together. This still isn't perfect though; the first number, since it doesn't begin with a comma, isn't processed.
Instead of checking for a comma, the better way is to check word boundaries, which can be done using \b. So the solution is:
import re
txt1 = "9.9,8.8,22.2,88.7,morris1.43#email.com,chat22.3#email.com,123.6,6.54"
txt1 = re.sub(r'\b(\d+)[.]\d+\b', r'\1',txt1)
print(txt1)
Considering these are the only two types of string that is present in your file, you can explicitly check for these conditions.
This may not be an efficient way, but what I have done is split the str and check if the string contains #email.com. If thats true, I am just appending to a new list. For your 1st condition to satisfy, we can convert the str to int which will eliminate the decimal points.
If you want everything back to a str variable, you can use .join().
Code:
txt1 = "9.9,8.8,22.2,88.7,morris1.43#email.com,chat22.3#email.com,123.6,6.54"
txt_list = []
for i in (txt1.split(',')):
if '#email.com' in i:
txt_list.append(i)
else:
txt_list.append(str(int(float(i))))
txt_new = ",".join(txt_list)
txt_new
Output:
'9,8,22,88,morris1.43#email.com,chat22.3#email.com,123,6'

Python Function with 2 values

Homework Question I am struggling with
Specification:
The third function you will write should be called ‘excelPrep’. Your function should take one (1) argument:
a string that will contain the Excel formula. The function should return two (2) values: first, a string
containing the modified Excel formula; and second an integer containing the number of dollar signs
removed.
Example Test Case:
excelPrep(‘=SUM($A$4:$A$12)’)
returns
=sum(a4:a12)
and
4
I will not write the entire code since this is stackoverflow and not homework helper so I think you should complete with your own mind.
The function should be something like:
Remove the $ by checking every letter in the string with for loop, at the same time add a number counter so that you can know how many $s you’ve removed. Making the input from =SUM($A$4:$A$12) into =SUM(A4:A12).
You could return the value now however if the assignment specified to make the letters in to lowercase. Make a new string variable and append all the letters from the function returned variable =SUM(A4:A12) check if the letter is a number if not .lower(). Which leaves you with =sum(a4:a12).
To return two values, in the end of your function type return stringVariable, integerVariable. Just be careful when ever you are calling the function, you will need to variables to store the outputs. Like: a, b = excelPrep(“=SUM($A$4:$A$12) which for your information a = “=sum(a4:a12)”, b = 4.
Hope that helps.

Find specific string in vector column Matlab

In my program I need to ask the user a string (ex: 'C4') and then obtain the corresponding index to that string on the following vector:
labels=['C2';'C#2';'D2';'D#2';'E2';'F2';'F#2';'G2';'G#2';'A2';'A#2';'B2';'C3';'C#3';'D3';'D#3';'E3';'F3';'F#3';'G3';'G#3';'A3';'A#3';'B3';'C4';'C#4';'D4';'D#4';'E4';'F4';'F#4';'G4';'G#4';'A4';'A#4';'B4';'C5';'C#5';'D5';'D#5';'E5';'F5';'F#5';'G5';'G#5';'A5';'A#5';'B5'];
To ask the string is simple, used input and it worked on octave, but to find the index I couldn't make it work. I tried using find, find(ismember( and also with a for cycle but nothing seems to work.
Appreciate the help
Thanks.
Use strcmp (and note labels should be a cell array, as the strings have different lengths):
labels = {'C2';'C#2';'D2';'D#2';'E2';'F2';'F#2';'G2';'G#2';'A2';'A#2';'B2';'C3';'C#3';'D3';'D#3';'E3';'F3';'F#3';'G3';'G#3';'A3';'A#3';'B3';'C4';'C#4';'D4';'D#4';'E4';'F4';'F#4';'G4';'G#4';'A4';'A#4';'B4';'C5';'C#5';'D5';'D#5';'E5';'F5';'F#5';'G5';'G#5';'A5';'A#5';'B5'};
str = 'C4';
index = find(strcmp(str,labels));
You can use strcmpi instead of strcmp if case is not important.

Array of Strings in Fortran 77

I've a question about Fortran 77 and I've not been able to find a solution.
I'm trying to store an array of strings defined as the following:
character matname(255)*255
Which is an array of 255 strings of length 255.
Later I read the list of names from a file and I set the content of the array like this:
matname(matcount) = mname
EDIT: Actually mname value is hardcoded as mname = 'AIR' of type character*255, it is a parameter of a function matadd() which executes the previous line. But this is only for testing, in the future it will be read from a file.
Later on I want to print it with:
write(*,*) matname(matidx)
But it seems to print all the 255 characters, it prints the string I assigned and a lot of garbage.
So that is my question, how can I know the length of the string stored?
Should I have another array with all the lengths?
And how can I know the length of the string read?
Thanks.
You can use this function to get the length (without blank tail)
integer function strlen(st)
integer i
character st*(*)
i = len(st)
do while (st(i:i) .eq. ' ')
i = i - 1
enddo
strlen = i
return
end
Got from here: http://www.ibiblio.org/pub/languages/fortran/ch2-13.html
PS: When you say: matname(matidx) it gets the whole string(256) chars... so that is your string plus blanks or garbage
The function Timotei posted will give you the length of the string as long as the part of the string you are interested in only contains spaces, which, if you are assigning the values in the program should be true as FORTRAN is supposed to initialize the variables to be empty and for characters that means a space.
However, if you are reading in from a file you might pick up other control characters at the end of the lines (particularly carriage return and/or line feed characters, \r and/or \n depending on your OS). You should also toss those out in the function to get the correct string length. Otherwise you could get some funny print statements as those characters are printed as well.
Here is my version of the function that checks for alternate white space characters at the end besides spaces.
function strlen(st)
integer i,strlen
character st*(*)
i = len(st)
do while ((st(i:i).eq.' ').or.(st(i:i).eq.'\r').or.
+ (st(i:i).eq.'\n').or.(st(i:i).eq.'\t'))
i = i - 1
enddo
strlen = i
return
end
If there are other characters in the "garbage" section this still won't work completely.
Assuming that it does work for your data, however, you can then change your write statement to look like this:
write(*,*) matname(matidx)(1:strlen(matname(matidx)))
and it will print out just the actual string.
As to whether or not you should use another array to hold the lengths of the string, that is up to you. the strlen() function is O(n) whereas looking up the length in a table is O(1). If you find yourself computing the lengths of these static strings often, it may improve performance to compute the length once when they are read in, store them in an array and look them up if you need them. However, if you don't notice the slowdown, I wouldn't worry about it.
Depending on the compiler that you are using, you may be able to use the trim() intrinsic function to remove any leading/trailing spaces from a string, then process it as you normally would, i.e.
character(len=25) :: my_string
my_string = 'AIR'
write (*,*) ':', trim(my_string), ':'
should print :AIR:.
Edit:
Better yet, it looks like there is a len_trim() function that returns the length of a string after it has been trimmed.
intel and Compaq Visual Fortran have the intrinsic function LEN_TRIM(STRING) which returns the length without trailing blanks or spaces.
If you want to suppress leading blanks or spaces, use "Adjust Left" i.e. ADJUSTF(STRING)
In these FORTRANs I also note a useful feature: If you pass a string in to a function or subroutine as an argument, and inside the subroutine it is declared as CHARACTER*(*), then
using the LEN(STRING) function in the subroutine retruns the actual string length passed in, and not the length of the string as declared in the calling program.
Example:
CHARACTER*1000 STRING
.
.
CALL SUBNAM(STRING(1:72)
SUBROUTINE SYBNAM(STRING)
CHARACTER*(*) STRING
LEN(STRING) will be 72, not 1000

Resources