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 years ago.
Improve this question
I have code
import random
lst = ['.']
string = 'o3oyrwrj0jtirvwp5sh57oed67d5zy'
print ''.join('%s%s' % (x, random.choice(lst) if random.random() > 0.5 else '') for x in string)
It generates string with random dots between symbols:
o3.oy.r.wrj.0jt.i.rv.w.p5sh57.oe.d6.7.d.5z.y
o3oyr.wr.j.0.j.ti.rvw.p5sh5.7o.e.d6.7.d5zy
o.3o.y.rw.r.j.0.jt.i.r.v.wp.5sh.5.7.oe.d6.7.d5.zy
I need to generate string with number of dots from 1 to 10, and except results
dot at the end 'o.3.oyrwrj.0.jt.irv.wp.5.s.h57oe.d.67.d.5.zy.'
dot in the begin 'o.3.oyrwrj.0.jt.irv.wp.5.s.h57oe.d.67.d.5.zy'
double+ dot 'o..3.oyrwrj.0.jt.irv.wp.5.s.h57oe.d.67.d.5.zy'
I need only from 1 up to 10dots (not 10+)
You can use random.sample to select a random set of indices at which you will insert a dot instead of drawing at each index.
Forming slices out of these indices and joining with '.'.join will prevent pairs of dots as well as heading and trailing dots if you exclude first and last indices.
from random import sample
def insert_dots(s, k):
indices = sorted(sample(range(1, len(s) - 1), k))
intervals = []
for i, j in zip([0] + indices, indices + [len(s)]):
intervals.append(s[i:j])
return '.'.join(intervals)
Example
s = 'foobar'
for _ in range(5):
print (insert_dots(s, 3))
Output
fo.o.ba.r
fo.ob.a.r
f.oob.a.r
fo.o.b.ar
fo.o.ba.r
If you need a random number of dots, you can then do this.
insert_dots(s, randint(1, 10))
You can use this if statement:
if string.startswith('.')
# Raise dot at the beginning exception
elif string.endswith('.'):
# Raise dot at the end exception
elif '..' in string:
# Raise double dot exception
Related
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 1 year ago.
Improve this question
Let s = "%2ABCDE" - get first 2 characters from string
then output should be "AB".
Need to get characters from string specified by numeral in string.
E.g. s1="%12ABCDERTYUIOPLKHGF" - get first 12 characters from string.
I tried to get digit using re.findall('\d+', string ), but this creates problem if my string would be "%2ABCD1".
Please suggest
s = "%2ABCDE"
number = ""
offset = 0
for i in range(len(s)):
if s[i] == "%":
continue
elif s[i].isdigit():
number += s[i]
else:
offset = i
break
print(s[offset:int(number) + offset])
Output: AB
A simpler way of doing this would be to do the following:
txt = "%2ABCDE"
number_list = [s for s in txt if s.isdigit()]
number_concate = int("".join(number_list))
txt_filtered = txt[len(number_list)+1:]
print(txt_filtered[:number_concate])
Outputs AB for string "%2ABCDE"
Outputs ABCDERTYUIOP for string "%12ABCDERTYUIOPLKHGF"
You are taking your string, doing a list comprehension of the string if the digit exists, then joining the list and changing this to an integer to allow for you to filter your string accordingly. Then you strip the string to only the characters and you have your answer printed out.
import re
s = '%2ABCDERTYUIOPLKHGF'
numeral_instruction = re.search(r'%\d+',s).group(0)
start = len(numeral_instruction)
stop = start + int(numeral_instruction[1:])
s[start:stop]
outputs
AB
You can get the position of the first non-digit character in the string (skipping the %) and use that as the basis to get the length and form a substring:
s1="%12ABCDERTYUIOPLKHGF"
i = next(i for i,c in enumerate(s1[1:],1) if not c.isdigit())
result = s1[i:i+int(s1[1:i])]
print(result)
ABCDERTYUIOP
If the first number in the string is not always at index 1, you can skip a variable number of characters using the same technique:
s1="*:%12ABCDERTYUIOPLKHGF"
start = next(i for i,c in enumerate(s1) if c.isdigit())
end = next(i for i,c in enumerate(s1[start:],start) if not c.isdigit())
result = s1[end:end+int(s1[start:end])]
print(result)
ABCDERTYUIOP
If you want to use the re module, you only need the first occurrence of a number, so use re.search() instead of re.findall():
import re
m = re.search(r"\d+",s1)
result = s1[m.end():m.end()+int(m.group())]
print(result)
ABCDERTYUIOP
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 2 years ago.
Improve this question
I have this string (61,62,63,64) and i want to tranform the string into (61,61,62,62,62,62,63,64).
I want to duplicate the numbers in the string n times, the 61 i want to duplicate twice, the 62 i want to duplicate four times, how do i code something that duplicates a number in the string n times?
Can you possible do something like have annother string that tells the computer how many times to duplicate each number? (61, 62, 63, 64,) (2,4,1,1)
if both your inputs are strings:
a = '(61, 62, 63, 64,)'
b = '(2,4,1,1)'
a = [i for i in a[1:-1].strip().replace(" ","").split(",")]
a.remove('')
b = [int(i) for i in b[1:-1].strip().replace(" ","").split(",")]
result = "("
for i in range(len(b)):
for j in range(b[i]):
result += a[i]
result += ", "
result = result.strip()[:-1]+")"
print(result)
Here is a possible solution (if rep is a string and not a tuple, you just need to do rep = eval(rep)):
s = "(61,62,63,64)"
rep = (2,4,1,1)
# convert the string to a tuple
t = eval(s)
# compute the result as a tuple
result = tuple(x for i, x in enumerate(t) for _ in range(rep[i]))
# convert the result into a string
result = str(result)
If you want something more compact:
s = "(61,62,63,64)"
rep = (2,4,1,1)
result = str(tuple(x for i, x in enumerate(eval(s)) for _ in range(rep[i])))
Be careful with using eval!! Check this question for more info.
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 3 years ago.
Improve this question
As part of a project I am working on, I would like write to rewrite strings such that:
Multiplication should be placed in between number and letter when they are not present.
The equation should be equal to zero.
If, Input : 2x+5ydh=4 then output : 2*x+5*ydh-4
If, Input: x*3df + d5jk = -12 then output: x*3*df + d*5*jk +12
I am thinking of searching for the positions of numbers and letter separately, and then see they follow each other before fixing multiplication, but is that pythonic enough?
Why don't you do something like the following code snippet? Instead of going through and searching for the positions of each digit or letter, just perform it all in one loop, which is more efficient. Basically, we go through the string character by character. If a digit follows a letter, or vice versa, then we add a '*'. Otherwise, continue searching.
Then, to do the '=' part, just assign the negation of the right hand side to the left hand side. This part is a temporary (easy) fix, but if you want a more foolproof fix, you'd have to do some legitimate parsing and evaluating of the right hand side to negate it.
def convert(inp: str):
# Edge case check
if len(inp) == 0: return inp
# Go through the string looking for where to place '*'s
# Add the first character
tmp = [inp[0]]
for i in range(1, len(inp)):
# If letter followed by digit or the reverse, then add a '*'
if (inp[i].isalpha() and inp[i - 1].isdigit()) or (inp[i].isdigit() and inp[i - 1].isalpha()):
tmp.append('*')
# Now add the current character
tmp.append(inp[i])
# Convert the resulting list back to a string
ans = ''.join(tmp)
# Now if the equal sign is present, split the result
# and negate the right hand side
if '=' in ans:
left, right = ans.split('=', 1)
ans = '{}-({})'.format(left, right)
# Return the answer
return ans
print(convert('2x+5ydh=4'))
print(convert('x*3df + d5jk = -12'))
Try this :
a = "2x+5ydh=4"
b = "x*3df + d5jk = -12"
def format_equation(inp_str):
lst = str("".join([c + "*" if (c.isnumeric() and d.isalpha()) else (c+"*" if (c.isalpha() and d.isnumeric()) else c) for c,d in zip(inp_str,inp_str[1:])]) + inp_str[-1]).split("=")
lhs = lst[0]
rhs = "+" + str(abs(int(lst[1]))) if int(lst[1]) <0 else "-" + str(lst[1])
return lhs + rhs
format_equation(a) # 2*x+5*ydh-4
format_equation(b) # x*3*df + d*5*jk +12
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 5 years ago.
Improve this question
Say I have a string (mystring). I want to extract all possible substrings of mystring so long as the substrings are lengths 8-15. I've been able to do that with no problem (see code below). However, what if I want to only extract these substrings if they overlap a certain part of mystring? The overlap is defined by the position in mystring rather than a certain letter of mystring, as the letters are not unique across mystring.
In the example below, I might want my substrings to include zero-based index 11.
mystring = "JACKANDJILLRANUPTHEHILLFORWATER"
substrings = set()
for i in range(0, len(mystring)):
for length in range(8,16):
ss = mystring[i:i+length]
if len(ss) == length:
substrings.add(ss)
Simple answer
You could check that 11 is included in [i, i + length) by checking i <= 11 < i + length:
mystring = "JACKANDJILLRANUPTHEHILLFORWATER"
substrings = set()
for i in range(0, len(mystring)):
for length in range(8,16):
ss = mystring[i:i+length]
if len(ss) == length and i <= 11 < i + length:
substrings.add(ss)
As set comprehension
You could do it like this:
substrings = {mystring[i:j]
for i in range(0, len(mystring))
for j in range(i + 8, min(i + 16, len(mystring)))
if i <= 11 < j}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
def tlower(str1):
list = list(str1)
final = ''
for char in range(0,len(str1)):
if list[char] in UPPERCASE:
for ascii in range(0,len(UPPERCASE)):
if list[char] == UPPERCASE[ascii]:
list[char] = LOWERCASE[ascii]
final += list[char]
return final
NOTE - UPPERCASE and LOWERCASE are strings of all upper/lowercase letters
NOTE - can NOT use any string functions built into python (Replace, etc..)
I have this function to turn any string into all lower case, (Yes i know there is a built in function..) But compared to my other string functions I have created, this is fairly long, any better approach I should take to do doing this?
UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
LOWERCASE = "abcdefghijklmnopqrstuvwxyz"
def to_lower(s, trans=dict(zip(UPPERCASE, LOWERCASE))):
return ''.join(trans.get(ch,ch) for ch in s)
print to_lower('This Is a TEST') # => 'this is a test'
Edit:
zip() takes two lists and returns pairs of values, ie
zip('ABC', 'abc') # => [('A','a'), ('B','b'), ('C','c')]
dict() makes a dictionary - in this case,
{'A':'a', 'B':'b', 'C':'c'}
trans.get(x, y) is a more compact way of saying as trans[x] if x in trans else y. In this case, "if you have a lowercase version of this letter, return it, otherwise give back the original letter".
and if you don't like .join, how about reduce?
from operator import add
def to_lower(s, trans=dict(zip(UPPERCASE, LOWERCASE))):
return reduce(add, (trans.get(ch,ch) for ch in s), '')
For completeness:
def to_lower(string):
ords = (ord(c) for c in string)
return ''.join(chr(o + 32 * (65 <= o <= 90)) for o in ords)