How to change a dictionary in to a string - string

def dict_to_str(d):
'''(dict) -> str
Returns a string containing each key and value in d. Keys and values
are separated by a space. Each key-value pair is separated by a
comma.
>>> dict_to_str({3:4, 5:6})
'3 4, 5 6'
'''

The following is in Python.
exDict = {1:3, 2:4}
# This will give you a string that looks like "{1: 3, 2: 4}".
stringDict = str(exDict)
At this point you have a string of the dict. What you need to do now is replace the curly brackets and colon with an empty space. This should give you the form you want.
for char in stringDict:
if char in "{}:":
stringDict = stringDict.replace(char, "")
That should do the trick.

Related

Groovy: tokenize string up to 3rd occurence of delimiter only

I want to tokenize string up to 3rd occurence of some delimiter and then return the rest of the string as last element of the tokenize array.
Example:
I have a String which looks like this:
String someString= 1.22.33.4
Now im tokenizing it by delimiter '.' like this:
def (a, b, c, d) = someString.tokenize('.')
And it works, but only if number of dots are exactly 3.
Now if someone puts more number of dots like:
String someString = 1.22.33.4.55
Then it wouldn't work, because the number of variables won't match. So i want to make sure it only tokenizes up to 3rd dot, and then gives back whatever is left. So what i want to achieve in this case would be:
a = 1, b=22, c=33, d=4.55
How to do that?
You can use the version of split with the second argument to restrict
the returned items. E.g.
def (a,b,c,d) = '1.22.33.4.55'.split("\\.", 4)
assert ["1","22","33","4.55"] == [a,b,c,d]
Not a one liner but it works:
String someString= '1.22.33.4.55'
def stringArray = someString.tokenize('.')
def (a,b,c) = stringArray
def d = stringArray.drop(3).join('.')
println "a=$a, b=$b, c=$c, d=$d"
result:
a=1, b=22, c=33, d=4.55

Replace non-numeric characters in string

I would like to know how to replace non-numeric characters in a single string with different random integers.
I have tried the following:
text = '1$1#387'
rec_1 = re.sub("\D+",str(random.randint(0,9)),text)
It then produced:
output: 1717387
As you can see, the non-numeric characters have been replaced by the same integer. I would like each non-numeric character to be replaced by a different integer. For example:
desired output: 1714387
Please assist.
Use a function as the replacement value:
def replacement(match):
return str(random.randint(0, 9))
text = '1$1#387'
rec_1 = re.sub(r"\D", replacement, text)
rec_1 is now "1011387", or "1511387", ...
That's because the randint function is called only 1 time.
You can use a lambda to get a new randint each time:
rec_1 = re.sub("\D+", lambda x: str(random.randint(0, 9)), text)

Zipping strings together at arbitrary index and step (Python)

I am working in Python 2.7. I am trying to create a function which can zip a string into a larger string starting at an arbitrary index and with an arbitrary step.
For example, I may want to zip the string ##*#* into the larger string TNAXHAXMKQWGZESEJFPYDMYP starting at the 5th character with a step of 3. The resulting string should be:
TNAXHAX#MK#QW*GZ#ES*EJFPYDMYP
The working function that I came up with is
#Insert one character of string every nth position starting after ith position of text
text="TNAXHAXMKQWGZESEJFPYDMYP"
def zip_in(string,text,i,n):
text=list(text)
for c in string:
text.insert(i+n-1,c)
i +=n
text = ''.join(text)
print text
This function produces the desired result, but I feel that it is not as elegant as it could be.
Further, I would like it to be general enough that I can zip in a string backwards, that is, starting at the ith position of the text, I would like to insert the string in one character at a time with a backwards step.
For example, I may want to zip the string ##*#* into the larger string TNAXHAXMKQWGZESEJFPYDMYP starting at the 22nd position with a step of -3. The resulting string should be:
TNAXHAXMKQW*GZ#ES*EJ#FP#YDMYP
With my current function, I can do this by setting n negative, but if I want a step of -3, I need to set n as -2.
All of this leads me to my question:
Is there a more elegant (or Pythonic) way to achieve my end?
Here are some related questions which don't provide a general answer:
Pythonic way to insert every 2 elements in a string
Insert element in Python list after every nth element
Merge Two strings Together at N & X
You can use some functions from the itertools and more_itertools libraries (make sure to have them) and combine them to get your result : chunked and izip_longest.
# Parameters
s1 = 'ABCDEFGHIJKLMNOPQ' # your string
s2 = '####' # your string of elements to add
int_from = 4 # position from which we start adding letters
step = 2 # we will add in elements of s2 each 2 letters
return_list = list(s1)[:int_from] # keep the first int_from elements unchanged
for letter, char in izip_longest(chunked(list(s1)[int_from:], step), s2, fillvalue=''):
return_list.extend(letter)
return_list.append(char)
Then get your string back by doing :
''.join(return_list)
Output :
# For the parameters above the output is :
>> 'ABCDEF#GH#IJ#KL#MNOPQ'
What does izip_longest(chunked(list(s1)[int_from:], step), s2, fillvalue='') return ?:
for letter, char in izip_longest(chunked(list(s1)[int_from:], step), s2, fillvalue=''):
print(letter, char)
>> Output
>> (['E', 'F'], '#')
(['G', 'H'], '#')
(['I', 'J'], '#')
(['K', 'L'], '#')
(['M', 'N'], '')
(['O', 'P'], '')
(['Q'], '')

Delete repeated pairs in a string

I have a string S='BDBCFBCFABDDEABCCDGAEAABCEAAHF'. The string S is combined by many pairs respectively such as : 'BD', 'BC', 'FB',...,'HF'.
How can I delete all of the repeated pairs in this string? I would like to delete the pairs which has the same characters as well such as 'AA','BB',...,'ZZ'
The output should be:
Out = 'BDBCFBCFABEABCCDGAEACEHF'
Depending on your restrictions maybe you're after:
U = unique(reshape(S,[],2),'rows','stable')
And from there you can delete rows of double letters like:
out = U(U(:,1)~=U(:,2),:)

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