How to convert from single character to string in Nim? - nim-lang

In Nim, I have a string that I need to split into characters, but each character should be converted to a string.
Right now I have something like:
var d = initTable[string,int]()
for ch in line:
d.mgetOrPut(ch, 0) += 1
This fails, because ch is a character, not a string. One option is to call initTable with char,int, but I would like to know: how can I convert ch in the example above to a string, so that it can be put into the table?

You can use $, for example:
import tables
from strformat import fmt
var line = "abc"
var table = {
"a": 2,
"b": 4,
"c": 8
}.toTable
for x in line:
# you can use '$' to convert the char 'x' into
# a single character string
# ref: https://nim-lang.org/docs/dollars.html#%24%2Cchar
echo fmt"{x} is {table[$x]}"
Reference https://nim-lang.org/docs/dollars.html#%24%2Cchar

Related

How to extract only the digits and print as a string

Here I want to extract 011700 (these are 6 digit codes) which I want to extract without the semi-colon and later I will use a dict for a value against it.
How do I extract only 011700 (or 6 digit number from that line)?
And how to print it as a 6 digit number - instead of printing it like ['011700']?
Thanks.
import re
line = "N 011700; 3;20:34:00:02:ac:07:e9:d5;2f:f7:00:02:ac:07:e9:d5; 3333"
line_list = line.split()
print(line_list)
result = (re.findall('\\d+', line))
print(result)
Here's how I would go about modifying your current code.
First, I would specify that you are trying to split the string by semicolons, by changing your split line to:
line_list = line.split(";")
Then I would trim off any whitespace, which you could do with a second line like:
line_list = [l.strip() for l in line_list]
(or by combining them like)
line_list = [l.strip() for l in line.split(";")]
Then I would simply loop through the list like so:
for l in line_list:
if len(l) == 6:
result = l
break
And if you want the result to be the actual number and not just a string of the number, change the line to:
result = int(l)
Altogether that would look like this:
line = "N 011700; 3;20:34:00:02:ac:07:e9:d5;2f:f7:00:02:ac:07:e9:d5; 3333"
line_list = [l.strip() for l in line.split(";")]
for l in line_list:
if len(l) == 6:
result = int(l)
break
print(line_list)
print(result)
Result now contains the string of the first six-digit number found in your original string.

Create a list of strings with one/multiple character replacement

How to create a whole list of string from one string where each string in the list containing exactly one character replacement? The string itself is consisted of only four characters (say: A, B, C, and D), so that the whole list of a string of length n would contain 3n+1 strings with exactly one character replacement.
Example:
inputstr = 'ABCD'
output = ['ABCD', 'BBCD', 'CBCD', 'DBCD', 'AACD', 'ACCD', 'ADCD', 'ABAD', 'ABBD', 'ABDD', 'ABCA', 'ABCB', 'ABCC']
I write the following python code:
strin = 'ABCD'
strout = set()
tempstr1 = ''
tempstr2 = ''
tempstr3 = ''
tempstr4 = ''
for base in range(len(strin)):
if strin[base] == 'A': #this block will be repeated for char B, C and D
tempstr1 = strin.replace(strin[base], 'A')
strout.add(tempstr1)
tempstr1 = ''
tempstr2 = strin.replace(strin[base], 'B')
strout.add(tempstr2)
tempstr2 = ''
tempstr3 = strin.replace(strin[base], 'C')
strout.add(tempseq3)
tempstr3 = ''
tempstr4 = strin.replace(strin[base], 'D')
strout.add(tempseq4)
tempstr4 = ''
return strout
and it works well as long as there is no repeated character (such as 'ABCD'). However, when the input string contains repeated character (such as 'AACD'), it will return less than 3n+1 string. I tried with 'AACD' string and it returns only 10 instead of 13 strings.
Anyone can help?
change
strout = set() ===> strout = list()
I found it. I used a slicing method to create a list of total combination of strings with one replacement.
for i in range(len(seq)):
seqxlist.append(seq[:i] + 'x' + seq[i+1:])
and after that I filter out all the x-replaced strings which are longer than the original string length:
seqxlist = [x for x in seqxlist if (len(x) == len(seq))]
Then, I changed x into any of the substitution characters:
for m in seqxlist:
tempseq1 = m.replace('x', 'A')
outseq.append(tempseq1)
tempseq2 = m.replace('x', 'B')
outseq.append(tempseq2)
tempseq3 = m.replace('x', 'C')
outseq.append(tempseq3)
tempseq4 = m.replace('x', 'D')
outseq.append(tempseq4)
This will create all the possible combinations of string replacement, but still contains duplicates. To remove duplicates, I use set() to the outseq list.

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 to change a dictionary in to a 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.

looping through each element of a string and handling wildcard cases in python

I want to find if string1 is substring of string2.
e.g. string1="abc", string2="afcabcdfg".
I want to add Wildcard cases, e.g. "*" can substitute "a" and "c", "y" can substitute "f" or "d". As a result, "*by" should be substring of "afcabcdfg".
What is general way to code it? How should I loop it?
For the example provided by you try using a dictionary to define all the replacements then loop over the characters of the string like this:
string2="afcabcdfg"
table = {'a': '*', 'c': '*', 'f': 'y', 'd': 'y'}
new_string = ''
for c in string2:
if c in table and table[c] not in new_string: new_string += table[c]
elif c not in table: new_string += c
Use re, and a little string manipulation to make yourself a regex.
import re
string1 = 'abc'
string2 = 'zbcdef'
wildcards = 'a'
# . is wildcard in a regex.
my_regex = string1.replace(wildcards, '.')
# If there is a match, re returns an object. We don't care
# about what info the object holds, just that it returns.
if re.match(my_regex, string2):
print "Success"
# If there's no match, None is returned.
if not re.match(my_regex, string3):
print "Also success"

Resources