I would like to replace each letter of the sentence entered by the user with something specific.
I tried it with the "replace" function, but the code is way too long, because I don't know how to make lowercase and uppercase letters in one, so the code doesn't get too long. Furthermore, I want a "+" sign between the new letters, but not at the beginning and end
a = 'new_a'
b = 'new_b'
c = 'new_c'
d = 'new_d'
e = 'new_e'
f = 'new_f'
g = 'new_g'
h = 'new_h'
i = 'new_i'
j = 'new_j'
k = 'new_k'
l = 'new_l'
m = 'new_m'
n = 'new_n'
o = 'new_o'
p = 'new_p'
q = 'new_q'
r = 'new_r'
s = 'new_s'
t = 'new_t'
u = 'new_u'
v = 'new_v'
w = 'new_w'
x = 'new_x'
y = 'new_y'
z = 'new_z'
input_string = input("Text: ")
new_string = input_string.replace('a', a).replace('b', b).replace('c', c).replace('d', d).replace('e', e)...
print(new_string)
You can use a regular expression replacement with a callback function that looks up the replacements in a dictionary.
import re
replacements = {'a': 'new_a', 'b': 'new_b', ..., 'A': 'new_A', 'B': 'new_B', ...}
new_string = re.sub('[a-z]', lambda match: replacements[match.group()], input_string)
Note that your code has other problems besides being repetitive. If the input string is
abc
the replacement of a, b, and c will produce
new_anew_bnew_c
Then the replacement of e will produce
nnew_ew_annew_ew_bnnew_ew_c
and when it gets to n it will become
new_nnew_new_ew_anew_nnew_new_ew_bnew_nnew_new_ew_c
and the final result after replacing the w will be:
nenew_w_nnenew_w_nenew_w_enew_w_anenew_w_nnenew_w_nenew_w_enew_w_bnenew_w_nnenew_w_nenew_w_enew_w_c
Related
I have a string and I need to replace "e" with "x" one at a time. For e.g.
x = "three"
Then the expected output is:
("thrxe", "threx")
and if I have 3 characters to replace, for e.g.
y = "threee"
Then the expected output will be:
("thrxee", "threxe", "threex")
I have tried this:
x.replace("e", "x", 1) # -> 'thrxe'
But not sure how to return the second string "threx".
Try this
x = "threee"
# build a generator expression that yields the position of "e"s
# change "e"s with "x" according to location of "e"s yielded from the genexp
[f"{x[:i]}x{x[i+1:]}" for i in (i for i, e in enumerate(x) if e=='e')]
['thrxee', 'threxe', 'threex']
You could use a generator to replace e with x sequentially through the string. For example:
def replace(string, old, new):
l = len(old)
start = 0
while start != -1:
start = string.find(old, start + l)
if start != -1:
yield string[:start] + new + string[start + l:]
z = replace('threee', 'e', 'x')
for s in z:
print(s)
Output:
thrxee
threxe
threex
Note I've generalised the code to allow for arbitrary length match and replacement strings, if you don't need that just replace l (len(old)) with 1.
def replace(string,old,new):
f = string.index(old)
l = list(string)
i = 0
for a in range(string.count(old)):
l[f] = new
yield ''.join(l)
l[f]=old
try:
f = string.index(old,f+1)
except ValueError:
pass
i+=1
z = replace('threee', 'e', 'x')
for a in z:
print(a)
OUTPUT
thrxee
threxe
threex
I am trying to separate characters in a string into three different groups:
ASCII
String.punctuation
characters that don't belong to categories mentioned above.
The string in question is: "Tämä on testi!!! Toimiiko, mitä?"
So far, I have written the following code:
import string
osat = "Tämä on testi!!! Toimiiko, mitä?"
x = string.punctuation
a = ""
b = ""
c = ""
for i in osat:
if i.isascii():
a += i
elif i in x:
b += i
elif i not in x and i not in a:
c += i
print(a)
print(b)
print(c)
and this piece of code prints this:
Tm on testi!!! Toimiiko, mit?
äää
Why does the code include eg. "!" in ASCII?
Why doesn't the code add spaces even though the string does have spaces?
you can use this code:
import string
osat = "Tämä on testi!!! Toimiiko, mitä?"
x = string.punctuation
a = ""
b = ""
c = ""
def isnt_ascii(s):
return all(ord(c) >= 128 for c in s)
for i in osat:
if is_ascii(i):
a += i
elif i in x:
b += i
elif i not in x and i not in a:
c += i
print(a)
print(b)
print(c)
is_ascii is good function for this get ascii detailes :
def isnt_ascii(s):
return all(ord(c) >= 128 for c in s)
Output:
äää
!!!,?
Tm on testi Toimiiko mit
So I'm trying to make a python script that takes a pattern (ex: c**l) where it'll return every iteration of the string (* = any character in the alphabet)...
So, we get something like: caal, cbal, ccal and so forth.
I've tried using the itertools library's product but I haven't been able to make it work properly. So after 2 hours I've decide to turn to Stack Overflow.
Here's my current code. It's not complete since I feel stuck
alphabet = list('abcdefghijklmnopqrstuvwxyz')
wildChar = False
tmp_string = ""
combinations = []
if '*' in pattern:
wildChar = True
tmp_string = pattern.replace('*', '', pattern.count('*')+1)
if wildChar:
tmp = []
for _ in range(pattern.count('*')):
tmp.append(list(product(tmp_string, alphabet)))
for array in tmp:
for instance in array:
combinations.append("".join(instance))
tmp = []
print(combinations)
You could try:
from itertools import product
from string import ascii_lowercase
pattern = "c**l"
repeat = pattern.count("*")
pattern = pattern.replace("*", "{}")
for letters in product(ascii_lowercase, repeat=repeat):
print(pattern.format(*letters))
Result:
caal
cabl
cacl
...
czxl
czyl
czzl
Use itertools.product
import itertools
import string
s = 'c**l'
l = [c if c != '*' else string.ascii_lowercase) for c in s]
out = [''.join(c) for c in itertools.product(*l)]
Output:
>>> out
['caal',
'cabl',
'cacl',
'cadl',
'cael',
'cafl',
'cagl',
'cahl',
'cail',
'cajl'
...
What I want is to generate a string in this specific format: l+l+l+d+d+d+d+l+d+l+l+l+l+d+d+d+d+l+d+l+l+l+l+d+d+d+d+l+d+l+l+l+l+d+d+d+d+l+d+l With each l and d being a different string or number.
The issue is when I try to generate, the whole thing is the same value/string. But I want it different.
Here is an example:
What I am getting:
lll9999l9llll9999l9llll9999l9llll9999l9l
What I need:
bfb7491w3anfr4530x2zzbg9891u2rbep8421m9s
def id_gen():
l = random.choice(string.ascii_lowercase)
d = random.choice(string.digits)
id = l+l+l+d+d+d+d+l+d+l+l+l+l+d+d+d+d+l+d+l+l+l+l+d+d+d+d+l+d+l+l+l+l+d+d+d+d+l+d+l
print(id)
The result:
lll9999l9llll9999l9llll9999l9llll9999l9l
I need this to generate something different :)
This seems to work for me:
def gen_id() :
pattern = 'lllddddldllllddddldllllddddldllllddddldl'
digits = [random.choice(string.digits) for i in range(len(pattern))]
letters = [random.choice(string.ascii_lowercase) for i in range(len(pattern))]
return ''.join( digits[i] if pattern[i] == 'd' else letters[i] for i in range(len(pattern)) )
testing:
>>> gen_id()
'lnx1066k0hnrd5409d1nhgo1254t6rzyw5165f8v'
>>> gen_id()
'sbc7119f4ythd8845i1afay1900f4wjcv0659b4e'
>>> gen_id()
'yan6228r0nebj5097y7jnwh7065s7osra0391j5f'
>>>
seems different enough... please, don't forget to import string, random =)
To not consume the random generator, IMHO this is the best solution:
def gen_id(pattern) :
l = len(pattern)
d = pattern.count('d')
digits = random.choices(string.digits, d)
letters = random.choices(string.ascii_lowercase, l-d)
return ''.join( digits.pop() if pattern[i] == 'd' else letters.pop() for i in range(l) )
You can use this to get a random combination of letters and digits in the desired order:
def letter():
return random.choice(string.ascii_lowercase)
def digit():
return random.choice(string.digits)
def id_gen():
return letter() + digit() + letter() + letter() # ldll
I am a beginner programmer and I am doing a task for school. The task is to assign 4 constant variables and then use a code to work out the value. Each value has a corresponding letter and the program is asking the user to type in 5 numbers then the program will return the word. The code is the following:
array = [["L","N"], #define the 2d array, L=Letters, N=Numbers
["-","-"]] #line for space
a = 2#define the variables
b = 1
c = 7
d = 4
e = (a*b)+b#calcualtions
f = c+b
g = (d/a)-b
h = c*a
i = a+b+d
j = c-a
k = c-d*f
l = c+a
m = (c*a)-b
n = a*d
o = a+d-b
p = (c*d)-a*(b+d)
q = a*(c+(d-b))
r = (d*d)-b
s = r-f-g
array.append(["e",e])
array.append(["f",f])
array.append(["g",g])#append all the calculations
array.append(["h",h])
array.append(["i",i])
array.append(["j",j])
array.append(["k",k])
array.append(["l",l])
array.append(["m",m])
array.append(["n",n])
array.append(["o",o])
array.append(["p",p])
array.append(["q",q])
array.append(["r",r])
array.append(["s",s])
def answer():
len_row = len(array)
number_input = int(input("Enter number: "))
for i in range(len_row):
if number_input == (array[i][1]):
return array[i][0]
break
one_let = answer()
two_let = answer()
thr_let = answer()
fou_let = answer()
fiv_let = answer()
print(one_let,two_let,thr_let,fou_let,fiv_let)
The numbers that I am meant to put in are 6, 18,, 7, 8, and 3.
The word that prints is "spife" and the word that is meant to be printed is "spine". The problem is that there are two letters that have a variable of 8 and Python gets the first one only. Is there a way to print out the two seperate words but first with the first variable in a 2D array and second with the second 2D array? i.e spife then spine
Thank you for your help ahead, I am just a beginner! :)
Yes you can do it but is a bit tricky the secret is to use itertools.product on the list of letters that could have each of the five values.
First you need to use a better data structure such as a dict, (in this case a collection.defaltdict) to hold the letters that have some value. You can do this way:
import collections
import itertools
a = 2#define the variables
b = 1
c = 7
d = 4
e = (a*b)+b#calcualtions
f = c+b
g = (d/a)-b
h = c*a
i = a+b+d
j = c-a
k = c-d*f
l = c+a
m = (c*a)-b
n = a*d
o = a+d-b
p = (c*d)-a*(b+d)
q = a*(c+(d-b))
r = (d*d)-b
s = r-f-g
dat = collections.defaultdict(list)
for c in "abcdefghijklmnopqrs":
dat[eval(c)].append(c)
Now in dat you have a list of letters that match some number, for example
print(dat[6])
print(dat[18])
print(dat[7])
print(dat[8])
print(dat[3])
Outputs:
['s']
['p']
['i']
['f', 'n']
['e']
OK, then you need to change answerto return a list of letters, and collect the user input:
def answer():
number_input = int(input("Enter number: "))
return dat[number_input]
letts = [answer() for _ in range(5)] #collect five answers of the user
And the final magic is done here:
for s in map(lambda x: "".join(x),itertools.product(*letts)):
print(s)
Now if you are confused then study:
collections
collections.defaultdict
itertools
itertools.product
str.join