How can I print only integers/numbers from string - string

Hello I am fairly new at programming and python and I have a question.
How would I go about printing or returning only numbers from a string
For example:
"Hu765adjH665Sdjda"
output:
"765665"

You can use re.sub to remove any character that is not a number.
import re
string = "Hu765adjH665Sdjda"
string = re.sub('[^0-9]', '', string)
print string
#'765665'
re.sub scan the string from left to right. everytime it finds a character that is not a number it replaces it for the empty string (which is the same as removing it for all practical purpose).

>>> s = "Hu765adjH665Sdjda"
>>> ''.join(c for c in s if c in '0123456789')
'765665'

a='a345g5'
for i in a:
if int(i.isnumeric()):
print(i,end=' ')

Try filter
>>> str='1qaz2wsx3edc4rfv5tgb6yhn7ujm8ik9ol'
>>> print str
1qaz2wsx3edc4rfv5tgb6yhn7ujm8ik9ol
>>> filter(lambda x:x>='0' and x<='9', str)
'123456789'

sentence = "Hu765adjH665Sdjda"
for number in sentence:
if number in "0123456789":
print(number)

Related

How can we skip some part in the string using regex

I have a string:
st="[~620cc13778d079432b9bc7b1:Hello WorldGuest]"
I just want the part after ":" and before "]". The part in between can have a maximum length of 64 characters.
The part after "[~" is 24 character UUID.
So the resulting string would be "Hello WorldGuest".
I'm using the following regex:
r"(\[\~[a-z0-9]{24}:)(?=.{0,64})"
But that is only matching the string till ":", I also want to match the ending "]".
Given:
>>> import re
>>> st = "[~620cc13778d079432b9bc7b1:Hello WorldGuest]"
Two simple ways:
>>> re.sub(r'[^:]*:([^\]]*)\]',r'\1',st)
'Hello WorldGuest'
>>> st.partition(':')[-1].rstrip(']')
'Hello WorldGuest'
If you want to be super specific:
>>> re.sub(r'^\[~[a-z0-9]{24}:([^\]]{0,64})\]$',r'\1',st)
'Hello WorldGuest'
If you want to correct your pattern, you can do:
>>> m=re.search(r'(?:\[~[a-z0-9]{24}:)(?=([^\]]{0,64})\])', st)
>>> m.group(1)
'Hello WorldGuest'
Or with anchors:
>>> m=re.search(r'(?:^\[~[a-z0-9]{24}:)(?=([^\]]{0,64})\]$)', st)
>>> m.group(1)
'Hello WorldGuest'
Note:
I just used your regex for a UUID even though it is not correct. The correct regex for a UUID is:
[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}
But that would not match your example...

Remove comma from substring in Python

The string is the following:
s = 'AUDC,AUDIOCODES COM,+55,27.49,26.47,"$1,455.85",($56.10),($56.10),-3.71%'
I would like the comma inside this substring "$1,455.85" to be removed but not the other commas.
I tried this but failed:
import re
pattern = r'$\d(,)'
re.sub(pattern, '', s)
Why doesn't this work?
You need a positive lookbehind assertion, i.e., match a comma if it is preceded by a $ (note that $ needs to be escaped as \$) followed by a digit (\d). Try:
>>> s = 'AUDC,AUDIOCODES COM,+55,27.49,26.47,"$1,455.85",($56.10),($56.10),-3.71%'
>>> pattern = r'(?<=\$\d),'
>>> re.sub(pattern, '', s)
'AUDC,AUDIOCODES COM,+55,27.49,26.47,"$1455.85",($56.10),($56.10),-3.71%'
import re
pattern = r"(\$\d+),"
s = 'AUDC,AUDIOCODES COM,+55,27.49,26.47,"$1,455.85",($56.10),($56.10),-3.71%'
print(s)
s = re.sub(pattern, r'\1', s)
print(s)
Output:
AUDC,AUDIOCODES COM,+55,27.49,26.47,"$1,455.85",($56.10),($56.10),-3.71%
AUDC,AUDIOCODES COM,+55,27.49,26.47,"$1455.85",($56.10),($56.10),-3.71%
But it doesn't work for "$1,455,789.85"

Python 3 stripping a string of certain characters which are in a list

How would one strip a string from characters which reside in a list? Eg
Striplist = ["+","-","!","*"];
StripString = "A+B*!-+C";
use str.translate():
>>> tab = str.maketrans('', '', ''.join(["+","-","!","*"]))
>>> "A+B*!-+C".translate(tab)
'ABC'
Strings are lists, so use list comprehension.
chars = [“+”, “-”, “.”]
str = “x+y=1.2”
newstr = [c for c in str if not c in chars]
Will yield “xy=12”

Python - check if string contains special characters, if yes, replace them

I am having a number of strings in the loop, some strings contain "," and some doesn't contain, I want my code to check if there is any "," present in a string remove them and then print the string, and if its not present, print the string as it is.
here is my code:
for x in range(y):
c = containers[x].find("div",{"class":"cong-data"})
meeting = c.p.next_element
print(meeting)
Thanks in advance.
I recommend using Regular Expression sub() function.
import re
string = 'aabcdefg,hijklmnop,qrstu,ssads'
remove_commas = re.sub(',', '', string)
print(string)
print(remove_commas)
output:
aabcdefg,hijklmnop,qrstu,ssads
aabcdefghijklmnopqrstussads

How can I delete the letter that occurs in the two strings using python?

That's the source code:
def revers_e(str_one,str_two):
for i in range(len(str_one)):
for j in range(len(str_two)):
if str_one[i] == str_two[j]:
str_one = (str_one - str_one[i]).split()
print(str_one)
else:
print('There is no relation')
if __name__ == '__main__':
str_one = input('Put your First String: ').split()
str_two = input('Put your Second String: ')
print(revers_e(str_one, str_two))
How can I remove a letter that occurs in both strings from the first string then print it?
How about a simple pythonic way of doing it
def revers_e(s1, s2):
print(*[i for i in s1 if i in s2]) # Print all characters to be deleted from s1
s1 = ''.join([i for i in s1 if i not in s2]) # Delete them from s1
This answer says, "Python strings are immutable (i.e. they can't be modified). There are a lot of reasons for this. Use lists until you have no choice, only then turn them into strings."
First of all you don't need to use a pretty suboptimal way using range and len to iterate over a string since strings are iterable you can just iterate over them with a simple loop.
And for finding intersection within 2 string you can use set.intersection which returns all the common characters in both string and then use str.translate to remove your common characters
intersect=set(str_one).intersection(str_two)
trans_table = dict.fromkeys(map(ord, intersect), None)
str_one.translate(trans_table)
def revers_e(str_one,str_two):
for i in range(len(str_one)):
for j in range(len(str_two)):
try:
if str_one[i] == str_two[j]:
first_part=str_one[0:i]
second_part=str_one[i+1:]
str_one =first_part+second_part
print(str_one)
else:
print('There is no relation')
except IndexError:
return
str_one = input('Put your First String: ')
str_two = input('Put your Second String: ')
revers_e(str_one, str_two)
I've modified your code, taking out a few bits and adding a few more.
str_one = input('Put your First String: ').split()
I removed the .split(), because all this would do is create a list of length 1, so in your loop, you'd be comparing the entire string of the first string to one letter of the second string.
str_one = (str_one - str_one[i]).split()
You can't remove a character from a string like this in Python, so I split the string into parts (you could also convert them into lists like I did in my other code which I deleted) whereby all the characters up to the last character before the matching character are included, followed by all the characters after the matching character, which are then appended into one string.
I used exception statements, because the first loop will use the original length, but this is subject to change, so could result in errors.
Lastly, I just called the function instead of printing it too, because all that does is return a None type.
These work in Python 2.7+ and Python 3
Given:
>>> s1='abcdefg'
>>> s2='efghijk'
You can use a set:
>>> set(s1).intersection(s2)
{'f', 'e', 'g'}
Then use that set in maketrans to make a translation table to None to delete those characters:
>>> s1.translate(str.maketrans({e:None for e in set(s1).intersection(s2)}))
'abcd'
Or use list comprehension:
>>> ''.join([e for e in s1 if e in s2])
'efg'
And a regex to produce a new string without the common characters:
>>> re.sub(''.join([e for e in s1 if e in s2]), '', s1)
'abcd'

Resources