Extracting a two digit number from a string in python - string

I need to extract a two digit number from a string in python3.
** e.g. string is "1234" and I want the middle two numbers so I get 23.**
This isn't limited to just four letters, it could be hundreds.
Please could someone help?
Thank you as always!

I have tried the following line of code and it works for me.
value = '1234'
print(value[1:-1])
Hope this helps.
Edit:
With some more char in it.
value = '1234567'
m = len(value)//2
print(value[m:m+2])

To extract two digits from the string "1234"
str function can be used.
Code:
stringparse="1234"
twodigit= stringparse[1]+stringparse[2]
print(twodigit)
Output
Out[180]: '23'

According to a quick Google search (this website), you should do:
String = "1234"
ChoppedString = String[1:3] #Remember, the first letter is 0, the second is 1, etc.
print(ChoppedString)
The [1:3] bit just means 'Start at the first letter, then get everything up to (but excluding) the second one.

Related

How to get the middle of a string in Python?

Hold on: It's not as easy as it sounds in the title.
I've been working on a very crude AI, and the seemingly hard bits have been easy but this one little function is being really hard.
What I want this to do is get some of the chars that occur before a chars in the string. For example,
get_piece_behind("Hello World", 5, 3) #Return the 3 chars that come before ' ' (the fifth char)
'llo'
get_piece_behind("Hello World", 4, 3) #Return the 3 chars that come before 'o' in "hello" (the fourth char)
'ell'
get_piece_behind("Hello World", 5, 2) #Return the 2 chars that come before the fifth char
'lo'
The code accepts a string, an int marking a place in the string, and an int telling the function how far back it should look.
I get the idea this should be a super-simple one-liner... but my coffee infused brain has been staring at it for the past hour, rewriting it over and over, and nothing seems to work (my current function returns small bits of string, but from the wrong place)
def get_piece_behind(string, place, length_of_piece): #My current function
string = string[(place - length_of_piece):]
string = string[:place]
return string
Does anyone know how to fix this? I get the idea that it's a tiny, stupid error that I will have completely overlooked.
Thanks!
Python strings are sequences, and as such you can use the slice-index syntax to retrieve sub-sequeces of it:
a = "hello world"
a[1:3] # retrieves the chars from the second posistion (index 1) up to the 4th.
# the same, but as you want, putting expressins to calculate the indexes:
a[5-3:5]
a[4-3:4]
I suggest you to read the following document in whole before proceeding with your task - might save you a lot of time:
https://docs.python.org/3/tutorial/introduction.html
You are overlooking in your string splicing.
Try this:
def get_piece_behind(string, place, length_of_piece):
string = string[(place-length_of_piece) : place]
return string
Just do it in one line :) since your string change after first reassignment, also character positions will change:
def get_piece_behind(_string, place, length_of_piece): #My current function
_string = _string[(place - length_of_piece):place]
return _string
The index of characters changes as you cut first with place - length_of_piece, which gives 2, so you were cutting from third char, "llo World" then 5 characters before, resulting in "llo W".
This should work for you:
def get_piece_behind(string, place, length_of_piece):
return string[place-length_of_piece:place]
Output:
llo
ell
lo

Python how to remove the first set of a character in a string?

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

Adding Hyphen within a spliced string

Continuing from my last question (which, btw, thanks for the help!), I'm stuck on how to add a hyphen to separate my string. Here's what I have so far:
original = "1234567890"
def fixPhoneNum(original):
original = list(original)
original[0], original[9] = original[9], original[0]
original[1:5], original[5:8] = original[5:8], original[1:5]
original = ''.join(original)
original = print(original[0:3], end="-"), print(original[3:7], end="-"), print(original[5:9])
return
Edit The above code doesn't give me the result I'm looking for
So basically, I took the original string of numbers, switched the first and last and the intermediary values with each other. Now I want to separate the first 3 digits, the next 3 digits with a hyphen.
Any help? This is driving me crazy.
Thanks!
I do not quite understand the rule for character ordering in your question.
Here is a simpler example of str.format function which accepts "0123" and produces "30-21" permutation with a hyphen. Hope it answers the question.
instr = "0123"
outstr = '{0[3]}{0[0]}-{0[2]}{0[1]}'.format(instr)
If you are not familiar with format strings, start with examples in the docs: https://docs.python.org/3/library/string.html#formatexamples

function to confirm the presence of both letters and numbers/ Ignoring excedents

So, I'm trying to build up a program with MATLAB according to some indications from my teacher and I came up with some obstacles which would give me a better grade if I could get them right. Here they are:
The user is asked to insert a string but it can't have more than 20 characters. If it does, the excedents will be ignored and the string is saved with the first 20 characters the user inserted. How do I ignore the excedents in a string and save it anyway?
isletter is a function that tells us if the elements are all letters. In this program, the user is asked to insert a string that needs to include both numbers and letters, so that strings with just letters or just numbers are excluded, and then I'll use a while to keep asking for a string with these characteristics.
Could you please help me? This is my first semester with MATLAB. Thank you!
If you want to disallow characters other than letters and numbers (i.e. '/#!' or whitespace) and require that the string they enter has to have at least 1 letter and 1 number, then you can use the ISSTRPROP function (which is more general than ISLETTER) to check for other types of characters. The idea to use INPUTDLG to prompt for the string (as suggested in Aabaz's answer) is a good one, so here's a nice condensed solution using INPUTDLG that achieves what you want:
answer = ''; %# Initialize answer to be an empty string
while any(~isstrprop(answer, 'alphanum')) || ... %# Check for alphanumeric chars
~any(isletter(answer)) || ... %# Check for at least 1 letter
~any(isstrprop(answer, 'digit')) %# Check for at least 1 number
answer = inputdlg('Enter string:'); %# Prompt for input
answer = answer{1}(1:min(20, end)); %# Trim answer to max of 20 chars
end
Note how the functions MIN and END are used to trim the string to 20 characters.
For the first part of your problem you can use the Matlab function inputdlg which prompts a dialog box asking for user input. Then you can trim the input as you like.
For the second part of your problem the function isletter that you mentioned will tell you for each character individually if they are alphabetic letters, so you could sum that result and check if it is between 1 and 19 for example. That will tell you that your string contains both letters and numbers.
Finally, you can put your code inside a while loop and change a variable when your conditions are met so that you can break outside of the loop.
This example code demonstrates this:
tryagain=1;
while(tryagain)
answer=inputdlg('Insert a 20 character string that contains both letters and numbers','User input');
answer=answer{1};
if(numel(answer)>20)
answer=answer(1:20);
end
letters=sum(isletter(answer));
numbers=sum(~arrayfun(#(x)isempty(str2num(x)),answer));
if(letters>0 && numbers>0)
tryagain=0;
end
end

Adding blank spaces into a string in C#

I have this code
String coNum = customerOrderLine.coNum.PadLeft(10 - customerOrderLine.coNum.Length);
I know that customerOrderLine.coNum = "123456" So I should end up with coNum being having 4 empty spaces at the front of it but I end up with it being "123456". How do I fix this? I tried PadRight in case that was the mistake and it also failed to work. I have to have the 4 empty spaces at the beginning to pass it into the API I am working on or it will fail.
PadLeft takes a total length as a parameter, so I think you want
String coNum = customerOrderLine.coNum.PadLeft(10);
This is because you have incorrectly specified the totalWidth parameter of the Pad* method.
From docs:
The number of characters in the resulting string, equal to the number
of original characters plus any additional padding characters.[...] If totalWidth is equal to the length of this instance, the method
returns a new string that is identical to this instance.
PadLeft does not specify a default character to pad with; your second argument should be the character to use for the pad, i.e.:
String coNum = customerOrderLine.coNum.PadLeft(10, ' ');
Edit: Also the first argument should be total desired length, not number of pad characters to add, per #Matthew's answer.

Resources