Can I connect the variables In a table? - string

For an example, lets say I have this table:
tbl = {"hi ", "my ", "name ", "is ", "King"}
Can I get this to return:
"hi my name is King"
Without
for k, v in ipairs( tbl )
print(v)
end
Because I am trying to process an unknown quantity of inputs, and compare the result to another string.

You can use table.concat() to get the result string:
local str = table.concat(tbl)
print(str)
It can do more, in particular, table.concat() takes a second optional parameter, which can be used as the separator, for instance, to use commas to separate each elements:
local str = table.concat(tbl, ',')
The biggest advantage of table.concat() versus direct string concatenation is performance, see PiL §11.6 for detail.

Related

How can I split a string in an array of strings such that each string is either a predefined array of strings, a variable or a string in Matlab?

I have two predefined arrays, say:
first = ["alpha" "beta"];
second = ["{" "}"];
and I want to create a function which receives a string and splits the string in different string arrays(or cell). Each array(or cell) should contain either a single member of one of the two arrays, a variable that is not a member of the arrays (without including the blank space) or a string. Ex:
Input string:
"alpha{ beta} new {} new2 "This is a string" }"
Output string:
"alpha" "{" "beta" "new" "{" "}" "new2" "This is a string" "}"
Hope it is clear!
Bests,
Stergios
I tried this:
S = "alpha{ beta} new new2 {} new3}";
T = ["alpha","beta", "{","}"];
[X,Y] = strsplit(S,[T " "], 'CollapseDelimiters',false);
X = strtrim(X); % you forgot to mention, that you also want to remove whitespace
X(2,:) = [Y,""];
X(strlength(X)==0) = []
but S does not accept strings of strings and if I use '' every word will be in a different cell!

Create a List with spaces without and not using .split()

I have to write an application that asks the user to enter a list of numbers separated by a space and then prints the sum of the numbers. The user can enter any number of numbers. I am not allowed to use the split function in python. I was wondering how I can do it that. Any help would be appreciated it as I'm kind of stuck on where to start.
Possible solution is to use regular expressions:
# import regular expression library
import re
# let user enter numbers and store user data into 'data' variable
data = input("Enter numbers separated by space: ")
"""
regular expression pattern '\d+' means the following:
'\d' - any number character,
'+' - one or more occurence of the character
're.findall' will find all occurrences of regular expression pattern
and store to list like '['1', '258', '475', '2', '6']'
please note that list items stored as str type
"""
numbers = re.findall(r'\d+', data)
"""
list comprehension '[int(_) for _ in numbers]' converts
list items to int type
'sum()' - summarizes list items
"""
summary = sum([int(_) for _ in numbers])
print(f'Sum: {summary}')
Another solution is following:
string = input("Enter numbers separated by space: ")
splits = []
pos = -1
last_pos = -1
while ' ' in string[pos + 1:]:
pos = string.index(' ', pos + 1)
splits.append(string[last_pos + 1:pos])
last_pos = pos
splits.append(string[last_pos + 1:])
summary = sum([int(_) for _ in filter(None, splits)])
print(f'Sum: {summary}')
From my point of view, the first option is more concise and better protected from user errors.

Python: Insert space between every element in a list with one line description in for loop

I am trying to write a simple Encrype and Decrype system. I have a syntax question like the topic above, please take a look.
def en_num(pw):
en1 = [int(x) for x in pw]
for i in en1:
numstr = "".join(bin(int(i))[2:])
numstr += " "
return numstr
For example, input is "1 2", the output will be "1 10"
This can geve me the right output, however, I am trying to write this for loop in one line, like this
def en_num(pw):
en1 = [int(x) for x in pw]
numstr = "".join(bin(int(i))[2:] for i in en1)
return numstr
I don't know how to add the space between in this syntax, the result is "110"
Please take a look, thanks!
Try adding a space between the quotes on your join statement:
numstr = " ".join(bin(int(i))[2:] for i in en1)
That will separate each number.

VBA: How to find the values after a "#" symbol in a string

I am trying to set the letters after a # symbol to a variable.
For example, x = #BAL
I want to set y = BAL
Or x = #NE
I want y = NE
I am using VBA.
Split() in my opinion is the easiest way to do it:
Dim myStr As String
myStr = "#BAL"
If InStr(, myStr, "#") > 0 Then '<-- Check for your string to not throw error
MsgBox Split(myStr, "#")(1)
End If
As wisely pointed out by Scott Craner, you should check to ensure the string contains the value, which he checks in this comment by doing: y = Split(x,"#")(ubound(Split(x,"#")). Another way you can do it is using InStr(): If InStr(, x, "#") > 0 Then...
The (1) will take everything after the first instance of the character you are looking for. If you were to have used (0), then this would have taken everything before the #.
Similar but different example:
Dim myStr As String
myStr = "#BAL#TEST"
MsgBox Split(myStr, "#")(2)
The message box would have returned TEST because you used (2), and this was the second instance of your # character.
Then you can even split them into an array:
Dim myStr As String, splitArr() As String
myStr = "#BAL#TEST"
splitArr = Split(myStr, "#") '< -- don't append the collection number this time
MsgBox SplitArr(1) '< -- This would return "BAL"
MsgBox SplitArr(2) '< -- This would return "TEST"
If you are looking for additional reading, here is more from the MSDN:
Split Function
Description Returns a zero-based, one-dimensional array containing a specified number of substrings. SyntaxSplit( expression [ ,delimiter [ ,limit [ ,compare ]]] ) The Split function syntax has thesenamed arguments:
expression
Required. String expression containing substrings and delimiters. If expression is a zero-length string(""), Split returns an empty array, that is, an array with no elements and no data.
delimiter
Optional. String character used to identify substring limits. If omitted, the space character (" ") is assumed to be the delimiter. If delimiter is a zero-length string, a single-element array containing the entire expression string is returned.
limit
Optional. Number of substrings to be returned; -1 indicates that all substrings are returned.
compare
Optional. Numeric value indicating the kind of comparison to use when evaluating substrings. See Settings section for values.
You can do the following to get the substring after the # symbol.
x = "#BAL"
y = Right(x,len(x)-InStr(x,"#"))
Where x can be any string, with characters before or after the # symbol.

Is there a way to substring, which is between two words in the string in Python?

My question is more or less similar to:
Is there a way to substring a string in Python?
but it's more specifically oriented.
How can I get a par of a string which is located between two known words in the initial string.
Example:
mySrting = "this is the initial string"
Substring = "initial"
knowing that "the" and "string" are the two known words in the string that can be used to get the substring.
Thank you!
You can start with simple string manipulation here. str.index is your best friend there, as it will tell you the position of a substring within a string; and you can also start searching somewhere later in the string:
>>> myString = "this is the initial string"
>>> myString.index('the')
8
>>> myString.index('string', 8)
20
Looking at the slice [8:20], we already get close to what we want:
>>> myString[8:20]
'the initial '
Of course, since we found the beginning position of 'the', we need to account for its length. And finally, we might want to strip whitespace:
>>> myString[8 + 3:20]
' initial '
>>> myString[8 + 3:20].strip()
'initial'
Combined, you would do this:
startIndex = myString.index('the')
substring = myString[startIndex + 3 : myString.index('string', startIndex)].strip()
If you want to look for matches multiple times, then you just need to repeat doing this while looking only at the rest of the string. Since str.index will only ever find the first match, you can use this to scan the string very efficiently:
searchString = 'this is the initial string but I added the relevant string pair a few more times into the search string.'
startWord = 'the'
endWord = 'string'
results = []
index = 0
while True:
try:
startIndex = searchString.index(startWord, index)
endIndex = searchString.index(endWord, startIndex)
results.append(searchString[startIndex + len(startWord):endIndex].strip())
# move the index to the end
index = endIndex + len(endWord)
except ValueError:
# str.index raises a ValueError if there is no match; in that
# case we know that we’re done looking at the string, so we can
# break out of the loop
break
print(results)
# ['initial', 'relevant', 'search']
You can also try something like this:
mystring = "this is the initial string"
mystring = mystring.strip().split(" ")
for i in range(1,len(mystring)-1):
if(mystring[i-1] == "the" and mystring[i+1] == "string"):
print(mystring[i])
I suggest using a combination of list, split and join methods.
This should help if you are looking for more than 1 word in the substring.
Turn the string into array:
words = list(string.split())
Get the index of your opening and closing markers then return the substring:
open = words.index('the')
close = words.index('string')
substring = ''.join(words[open+1:close])
You may want to improve a bit with the checking for the validity before proceeding.
If your problem gets more complex, i.e multiple occurrences of the pair values, I suggest using regular expression.
import re
substring = ''.join(re.findall(r'the (.+?) string', string))
The re should store substrings separately if you view them in list.
I am using the spaces between the description to rule out the spaces between words, you can modify to your needs as well.

Resources