Most Pythonic way to extract a number from a string [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have a string containing a number, starting with x, for example, "x270" or "x9". It always starts with x. I need to get the number.
I'm doing this:
blatz = "x22"
a1 = int(re.search("x(\d+)", blatz).group(1))
This doesn't seem very Pythonic. I would welcome more elegant solutions.

Using re library seems to be an overkill. You don't have to search for a pattern, because you're saying that each string starts with x.
So you simply can do slicing:
blatz = "x22"
a1 = int(blatz[1:])
If you need further checks, you can look at str.startswith(), str.endswith and/or str.isdigit().
While slicing looks very pythonistic, there is also the possibility to use other string methods that lead to the same goal:
blatz = "x22"
a2 = int(blatz.lstrip("x")) # strip "x" from the left
a3 = int(blatz.partition("x")[-1]) # get everything after "x"
a4 = int(blatz.replace("x", "")) # replace every "x" with empty string
...
But slicing is faster and nothing unusual for Python programmers.

Please check out this.
import re
blatz = "x22"
print(re.search("\d", blatz).group())

Related

How to unify all the "-" signs? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 months ago.
Improve this question
I have a simple program that takes data from the user. Here is an abbreviated version of it:
a = "0-1"
b = "0‑1"
print(a in b) # prints False
Problem:
ord('-') for a = 45
ord('‑') for b = 8209
How can I make sure that the "-" sign is always the same and checking a in b returns True?
The most robust way would be to use the unidecode module to convert all non-ASCII characters to their closest ASCII equivalent automatically.
import unidecode
print(unidecode.unidecode(a) in unidecode.unidecode(b))
It's not clear if your example is part of a more general, but for the example provided you can handle this using replace:
a = "0-1"
b = "0‑1"
print(a.replace("‑", "-") in b.replace("‑", "-")) # True
I've called replace on both sides, because it's not clear which side is your input and which is not. In principle though this comes down to "sanitize your input".
If this is more of a general problem, you might want to look at using .translate to produce a mapping of characters to apply in one go.

Finding a combination of characters and digits in a string python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 months ago.
Improve this question
I have a list of lists, and I'm attempting to loop through and check to see if the strings in a specific index in each of the inner lists contain a combination of "XY" and then 4 numbers immediately following. The "XY" could be in various locations of the string, so I'm struggling with the syntax beyond just using "XY" in row[5]. How to I add the digits after the "XY" to check? Something that combines the "XY" and isdigit()? Am I stuck using the find function to return an index and then going from there?
You can use Python's regex module re with this pattern that matches XY and then four digits anywhere in the string.
import re
pattern = r'XY\d{4}'
my_list = [['XY0'],['XY1234','AB1234'],['XY1234','ABC123XY5678DEF6789']]
elem_to_check = 1
for row in my_list:
if len(row) > elem_to_check:
for found in re.findall(pattern, row[elem_to_check]):
print(f'{found} found in {row[elem_to_check]}')
Output:
XY5678 found in ABC123XY5678DEF6789

How to selectively replace characters in a string? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
How would I replace characters in a string for certain indices in Python?
For example, I have version = "00.00.00" and need to change each of the 0s to a different value, say 3, to look like "33.33.33". Also, would this be possible if I had a variable storing this value. If I have vnumber = "3", would I be able to get the same output by using the variable? I'm sure replace() is a good function to use for this, but I'm not sure about syntax.
From an interactive session, you could type:
>>> help(str.replace)
But to answer the question most directly:
vnumber = '3'
newversion = version.replace('0', vnumber)
Is probably what you want to do.
Your guess about str.replace was right. It takes to arguments, the first is the string to be found in the original string, and the second is the string to replace the found occurrences of the first argument with. Code could be like this:
vnumber = "3"
version = "00.00.00"
newversion = version.replace("0", vnumber)
print(newversion)

Using the strip function to strip integer at the ends of a string [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I want to strip 0 from a given string.
The string contains either 1 or 0. I want to strip the zeroes if they appear at the ends.
I know i can do this using if condition, but i want to know if there is any function made to do this efficiently than using if-else.
Example-
String = 0100010101010
Output = 10001010101
Also, i don't think using regex is any more efficient, complexity wise.
Try this:
s = "0100010101010"
print(s.lstrip("0").rstrip("0"))
'10001010101'
This should work for the string s:
s = s.strip("0")
Make sure s is a string and not a number.
Can you try this , it will work
s = str(s).strip("0")

Test case in python like C programming language [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
How can I write following while loop in python?
int v,t;
while (scanf("%d %d",&v,&t)==2)
{
//body
}
Python being a higher level language than C will normally use different patterns for this kind of situation. There is a deleted question that in fact had the exact same behavior than your C snippet - and thus would be "correct", but it became so ugly a piece of code in Python it was downvoted pretty fast.
So, first things first - it is 2015, and people can't simply look at a C's "scanf" on the prompt and divine they should type two white space separated integer numbers - you'd better give then a message. Anther big difference is that in Python variable assignments are considered statements, and can't be done inside an expression (the while expression in this case). So you have to have a while expression that is always true, and decide whether to break later.
Thus you can go with a pattern like this.
while True:
values = input("Type your values separated by space, any other thing to exit:").split()
try:
v = int(values[0])
t = int(values[1])
except IndexError, ValueError:
break
<body>
This replaces the behavior of your code:
import re
while True:
m = re.match("(\d) (\d)", input()):
if m is None: #The input did not match
break #replace it with an error message and continue to let the user try again
u, v = [int(e) for e in m.groups()]
pass #body

Categories

Resources