Return 2(2) to 2*(2) - python

If a number is followed by "(" in a string:
How do I Replace it with number*(
Ex: input:"2(3+4)"
Output: "2*(3+4)"

to make sure that you replace only after digit you can loop over the string like this:
input = "2(3(8(12))+4)"
output = input
indices_to_insert = []
for i in range(len(input)-1):
if input[i].isdigit() and input[i+1] == '(':
indices_to_insert.append(i)
for iter,index in enumerate(indices_to_insert):
output = output[:index+iter+1] + "*" + output[index+iter+1:]
print(output)
output:
2*(3*(8*(12))+4)
you can also use regex

You can also use a regular expression substitution:
import re
s = '2(3+4)'
s = re.sub(r'(\d+)\(', r'\1*(', s)
print(s)
Prints:
2*(3+4)
Regex Demo and Explanation

Or you can try a bit shorter code that uses re
import re
s = '12(3+4)+5(4+1)-3(2(6/(1+1)))'
for m in re.findall('(\d+)(\()', s):
s = s.replace(''.join(m), '*'.join(m))
print(s)
'12*(3+4)+5*(4+1)-3*(2*(6/(1+1)))'

Related

How to get the substring between two markers in Python multiple times?

I have the following code:
s = '''alt="Thunder Force"/>ehkjehkljhiflealt="Godzilla vs. Kong"/>'''
for i in s:
start = s.find('alt="') + len('alt="')
end = s.find('"/>')
substring = s[start:end]
print(substring)
But it only prints out "Thunder Force" a lot of times. I would like that it finds "Thunder Force" and "Godzilla vs. Kong" and print those two once each. How?
you can use regex
import re
s = '''alt="Thunder Force"/>ehkjehkljhiflealt="Godzilla vs. Kong"/>'''
x = re.findall(r'alt="(.*?)"/>', s)
print(x)
output
['Thunder Force', 'Godzilla vs. Kong']
Use regex and re.findall()
s = '''alt="Thunder Force"/>ehkjehkljhiflealt="Godzilla vs. Kong"/>'''
print(re.findall(r'(?<=alt\=").*?(?="/>)', s))
#['Thunder Force', 'Godzilla vs. Kong']
Here's a non-regex solution that looks more like what I think you were trying to achieve with your posted attempt:
start = 0
while True:
start = s.find('alt="', start)
if start == -1:
break
start += len('alt="')
end = s.find('"/>', start)
if end == -1:
break
substring = s[start:end]
start = end
print(substring)
You could also use a negated character class [^"]+ to match any char except " and repeat it 1+ times if you want to match at least a single character.
If an empty match is also ok, you can use * instead of +.
import re
s = '''alt="Thunder Force"/>ehkjehkljhiflealt="Godzilla vs. Kong"/>'''
x = re.findall(r'alt="([^"]+)"/>', s)
print(x)
Output
['Thunder Force', 'Godzilla vs. Kong']

Python conditional replace

I need conditional replace in string.
input_str = "a111a11b111b22"
condition : ("b" + any number + "b") to ("Z" + any number)
output_str = "a111a11Z11122"
maybe I need to use [0] and [-1] for remove "b"s and "Z"+any number
but I can't find conditional replace for it.
You should use regular expressions. They are really useful:
import re
input_str = "a111a11b111b22"
output_str = re.sub(r'b(\d+)b', r'Z\1', input_str)
# output_str is "a111a11Z11122"
The r'b(\d+)b' regexpr matches letter b, followed by 1 or more digits and other letter b. The parenthesis memorizes the digits for further use (with \1) in the replacement part of the sentence (letter Z and \1).
Try with regex:
import re
input_str = "a111a11b111b22"
output_str = re.sub(r'[b](\d)',r'Z\1',input_str)
print(output_str)

Splitting Python string

Split the string into pairs of two characters. If the string contains an odd number of characters, then the missing second character of the final pair should be replaced with an underscore ('_').
Input: A string.
Output: An iterable of strings.
Example:
split_pairs('abcd') == ['ab', 'cd']
split_pairs('abc') == ['ab', 'c_']
import textwrap
def split_pairs(input):
# Use textwrap to split the input into chunks of two characters
split = textwrap.wrap(input, 2)
# In your example I see you want a "_" if string is odd length
# Check the length of the last chunk, and if it is 1, add a "_"
if len(split[-1]) == 1:
split[-1] += "_"
return split
print(split_pairs('abcd'))
print(split_pairs('abc'))
st = input('Input a string:')
arr = []
if len(st)%2==0:
for i in range(0,len(st)-1,2):
arr.append(st[i]+st[i+1])
else:
st +='_'
for i in range(0,len(st)-1,2):
arr.append(st[i]+st[i+1])
print(arr)
also if you want to enter a long text and strip white spaces after it try st = st.replace(' ','') after the input:
st = input('Input a string:')
st = st.replace(' ','')
arr = []
if len(st)%2==0:
for i in range(0,len(st)-1,2):
arr.append(st[i]+st[i+1])
else:
st +='_'
for i in range(0,len(st)-1,2):
arr.append(st[i]+st[i+1])
print(arr)
Try this short function without imports:
def split_pairs(inp):
pairs = [inp[2*i:2*i+2] for i in range(len(inp) // 2)]
if len(inp) % 2 == 1:
pairs.append(f'{inp[-1]}_')
return pairs
My solution is:
import re
def solution(s):
return re.findall(".{2}", s + "_")

Insert string before first occurence of character

So basically I have this string __int64 __fastcall(IOService *__hidden this);, and I need to insert a word in between __fastcall (this could be anything) and (IOService... such as __int64 __fastcall LmaoThisWorks(IOService *__hidden this);.
I've thought about splitting the string but this seems a bit overkill. I'm hoping there's a simpler and shorter way of doing this:
type_declaration_fun = GetType(fun_addr) # Sample: '__int64 __fastcall(IOService *__hidden this)'
if type_declaration_fun:
print(type_declaration_fun)
type_declaration_fun = type_declaration_fun.split(' ')
first_bit = ''
others = ''
funky_list = type_declaration_fun[1].split('(')
for x in range(0, (len(funky_list))):
if x == 0:
first_bit = funky_list[0]
else:
others = others + funky_list[x]
type_declaration_fun = type_declaration_fun[0] + ' ' + funky_list[0] + ' ' + final_addr_name + others
type_declaration_fun = type_declaration_fun + ";"
print(type_declaration_fun)
The code is not only crap, but it doesn't quite work. Here's a sample output:
void *__fastcall(void *objToFree)
void *__fastcall IOFree_stub_IONetworkingFamilyvoid;
How could I make this work and cleaner?
Notice that there could be nested parentheses and other weird stuff, so you need to make sure that the name is added just before the first parenthesis.
You can use the method replace():
s = 'ABCDEF'
ins = '$'
before = 'DE'
new_s = s.replace(before, ins + before, 1)
print(new_s)
# ABC$DEF
Once you find the index of the character you need to insert before, you can use splicing to create your new string.
string = 'abcdefg'
string_to_insert = '123'
insert_before_char = 'c'
for i in range(len(string)):
if string[i] == insert_before_char:
string = string[:i] + string_to_insert + string[i:]
break
What about this:
s = "__int64__fastcall(IOService *__hidden this);"
t = s.split("__fastcall",1)[0]+"anystring"+s.split("__fastcall",1)[1]
I get:
__int64__fastcallanystring(IOService *__hidden this);
I hope this is what you want. If not, please comment.
Use regex.
In [1]: import re
pattern = r'(?=\()'
string = '__int64 __fastcall(IOService *__hidden this);'
re.sub(pattern, 'pizza', string)
Out[1]: '__int64 __fastcallpizza(IOService *__hidden this);'
The pattern is a positive lookahead to match the first occurrence of (.
x='high speed'
z='new text'
y = x.index('speed')
x =x[:y] + z +x[y:]
print(x)
>>> high new textspeed
this a quick example, please be aware that y inclusuve after the new string.
be Aware that you are changing the original string, or instead just declare a new string.

Python - How to clear spaces from a text

In Python, I have a lot of strings, containing spaces.
I would like to clear all spaces from the text, except if it is in quotation marks.
Example input:
This is "an example text" containing spaces.
And I want to get:
Thisis"an example text"containingspaces.
line.split() is not good, I think, because it clears all of spaces from the text.
What do you recommend?
For the simple case that only " are used as quotes:
>>> import re
>>> s = 'This is "an example text" containing spaces.'
>>> re.sub(r' (?=(?:[^"]*"[^"]*")*[^"]*$)', "", s)
'Thisis"an example text"containingspaces.'
Explanation:
[ ] # Match a space
(?= # only if an even number of spaces follows --> lookahead
(?: # This is true when the following can be matched:
[^"]*" # Any number of non-quote characters, then a quote, then
[^"]*" # the same thing again to get an even number of quotes.
)* # Repeat zero or more times.
[^"]* # Match any remaining non-quote characters
$ # and then the end of the string.
) # End of lookahead.
There is probably a more elegant solution than this, but:
>>> test = "This is \"an example text\" containing spaces."
>>> '"'.join([x if i % 2 else "".join(x.split())
for i, x in enumerate(test.split('"'))])
'Thisis"an example text"containingspaces.'
We split the text on quotes, then iterate through them in a list comprehension. We remove the spaces by splitting and rejoining if the index is odd (not inside quotes), and don't if it is even (inside quotes). We then rejoin the whole thing with quotes.
Using re.findall is probably the more easily understood/flexible method:
>>> s = 'This is "an example text" containing spaces.'
>>> ''.join(re.findall(r'(?:".*?")|(?:\S+)', s))
'Thisis"an example text"containingspaces.'
You could (ab)use the csv.reader:
>>> import csv
>>> ''.join(next(csv.reader([s.replace('"', '"""')], delimiter=' ')))
'Thisis"an example text"containingspaces.'
Or using re.split:
>>> ''.join(filter(None, re.split(r'(?:\s*(".*?")\s*)|[ ]', s)))
'Thisis"an example text"containingspaces.'
Use regular expressions!
import cStringIO, re
result = cStringIO.StringIO()
regex = re.compile('("[^"]*")')
text = 'This is "an example text" containing spaces.'
for part in regex.split(text):
if part and part[0] == '"':
result.write(part)
else:
result.write(part.replace(" ", ""))
return result.getvalue()
You can do this with csv as well:
import csv
out=[]
for e in csv.reader('This is "an example text" containing spaces. '):
e=''.join(e)
if e==' ': continue
if ' ' in e: out.extend('"'+e+'"')
else: out.extend(e)
print ''.join(out)
Prints Thisis"an example text"containingspaces.
'"'.join(v if i%2 else v.replace(' ', '') for i, v in enumerate(line.split('"')))
quotation_mark = '"'
space = " "
example = 'foo choo boo "blaee blahhh" didneid ei did '
formated_example = ''
if example[0] == quotation_mark:
inside_quotes = True
else:
inside_quotes = False
for character in example:
if inside_quotes != True:
formated_example += character
else:
if character != space:
formated_example += character
if character == quotation_mark:
if inside_quotes == True:
inside_quotes = False
else:
inside_quotes = True
print formated_example

Categories

Resources