heres the question:
Remove First and Last Character
It's pretty straightforward. Your goal is to create a function that removes the first and last characters of a string. You're given one parameter, the original string. You don't have to worry with strings with less than two characters.
i have no idea how to do it because of the fact that it wants me to remove first and last letter and not the first and last word
Slicing is the best way to go about that.
test_string = 'This is a test!'
print (test_string [1:-1])
From your response that removing the first and last word would be done by list1.pop() and list1.pop(0) I am assuming that you are given a list of strings and are required to remove the first and last character of each string in the list.
If my assumption is correct you can do a combination of slicing and list comprehension.
list_of_str = ["words", "words", "words", "words"]
list_of_shortened_str = [word[1:-1] for word in list_of_str]
# list_of_shortened_str = ["ord", "ord", "ord", "ord"]
Related
I have a list of strings, and I'm trying to find the position of the first letter of the substring I am searching for in the list of strings. I'm using the find() method to do this, however when I try to print the position of the first letter Python returns the correct position but then throws a -1 after it, like it couldn't find the substring, but only after it could find it. I want to know how to return the position of the first letter of he substring without returning a -1 after the correct value.
Here is my code:
mylist = ["blasdactiverehu", "sdfsfgiuyremdn"]
word = "active"
if any(word in x for x in mylist) == True:
for x in mylist:
position = x.find(word)
print(position)
The output is:
5
-1
I expected the output to just be:
5
I think it may be related to the fact the loop is searching for the substring for every string in the list and after it's found the position it still searches for more but of course returns an error as there is only one occurrence of the substring "active", however I'm not sure how to stop searching after successfully finding one substring. Any help is appreciated, thank you.
Indeed your code will not work as you want it to, since given that any of the words contain the substring, it will do the check for each and every one of them.
A good way to avoid that is using a generator. More specifically, next()
default_val = '-1'
position = next((x.find(word) for x in mylist if word in x), default_val)
print(position)
It will simply give you the position of the substring "word" for the first string "x" that will qualify for the condition if word in x, in the list 'mylist'.
By the way, no need to check for == True when using any(), it already returns True/False, so you can simply do if any(): ...
I have a problem with splitting string into two parts on special character.
For example:
12345#data
or
1234567#data
I have 5-7 characters in first part separated with "#" from second part, where are another data (characters,numbers, doesn't matter what)
I need to store two parts on each side of # in two variables:
x = 12345
y = data
without "#" character.
I was looking for some Lua string function like splitOn("#") or substring until character, but I haven't found that.
Use string.match and captures.
Try this:
s = "12345#data"
a,b = s:match("(.+)#(.+)")
print(a,b)
See this documentation:
First of all, although Lua does not have a split function is its standard library, it does have string.gmatch, which can be used instead of a split function in many cases. Unlike a split function, string.gmatch takes a pattern to match the non-delimiter text, instead of the delimiters themselves
It is easily achievable with the help of a negated character class with string.gmatch:
local example = "12345#data"
for i in string.gmatch(example, "[^#]+") do
print(i)
end
See IDEONE demo
The [^#]+ pattern matches one or more characters other than # (so, it "splits" a string with 1 character).
scala has a standard way of splitting a string in StringOps.split
it's behaviour somewhat surprised me though.
To demonstrate, using the quick convenience function
def sp(str: String) = str.split('.').toList
the following expressions all evaluate to true
(sp("") == List("")) //expected
(sp(".") == List()) //I would have expected List("", "")
(sp("a.b") == List("a", "b")) //expected
(sp(".b") == List("", "b")) //expected
(sp("a.") == List("a")) //I would have expected List("a", "")
(sp("..") == List()) // I would have expected List("", "", "")
(sp(".a.") == List("", "a")) // I would have expected List("", "a", "")
so I expected that split would return an array with (the number a separator occurrences) + 1 elements, but that's clearly not the case.
It is almost the above, but remove all trailing empty strings, but that's not true for splitting the empty string.
I'm failing to identify the pattern here. What rules does StringOps.split follow?
For bonus points, is there a good way (without too much copying/string appending) to get the split I'm expecting?
For curious you can find the code here.https://github.com/scala/scala/blob/v2.12.0-M1/src/library/scala/collection/immutable/StringLike.scala
See the split function with the character as an argument(line 206).
I think, the general pattern going on over here is, all the trailing empty splits results are getting ignored.
Except for the first one, for which "if no separator char is found then just send the whole string" logic is getting applied.
I am trying to find if there is any design documentation around these.
Also, if you use string instead of char for separator it will fall back to java regex split. As mentioned by #LRLucena, if you provide the limit parameter with a value more than size, you will get your trailing empty results. see http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String,%20int)
You can use split with a regular expression. I´m not sure, but I guess that the second parameter is the largest size of the resulting array.
def sp(str: String) = str.split("\\.", str.length+1).toList
Seems to be consistent with these three rules:
1) Trailing empty substrings are dropped.
2) An empty substring is considered trailing before it is considered leading, if applicable.
3) First case, with no separators is an exception.
split follows the behaviour of http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)
That is split "around" the separator character, with the following exceptions:
Regardless of anything else, splitting the empty string will always give Array("")
Any trailing empty substrings are removed
Surrogate characters only match if the matched character is not part of a surrogate pair.
I wanted to know how to remove first character of a string in octave. I am manipulating the string in a loop and after every loop, I want to remove the first character of the remaining string.
Thanks in advance.
If it's just a one-line string then:
short_string = long_string(2:end)
But if you have a cell array of strings then either do it as above if you have a loop already, otherwise you can use this shorthand to do it in one line:
short_strings = cellfun(#(x)(x(2:end)), long_strings, 'uni', false)
Or else if you have a matrix of strings (i.e. all the same length), then you can vectorize it as:
short_strings = long_strings(:, 2:end)
AWESOME :)
Another QUESTION:
What if I have multiple Sentences like:
[PROGRAMMING]-Old System-TRT Operates-192.168.6.0-qwert8-plain (AMB)
[PATCHING]-Old System-TRT Operates-192.168.6.0-qwert8-plain (CCB)
Notice that the last word that I need to take out varies from sentence to sentence. How can i make sure that I always take out the last part of the sentence. In this case; (AMB) and (CCB)
I also need to do the same with the words at the beginning:
[PROGRAMMING]
[PATCHING]
Thanks :)
You can use this for the part within []:
=MID(A2,2,FIND("]",A2)-2)
And this for the part within ():
=MID(A2,FIND("(",A2)+1,3)
googlespreadsheet sample
MID takes 3 parameters:
A text,
A starting position,
The length of the extracted text.
FIND takes 2-3 parameters and returns a position number:
Something it will look for,
The text in which it will look for the something,
The position from where it'll start looking. If not mentioned, looks from the beginning.
=MID(A2,2,FIND("]",A2)-2) with your first example becomes the following after replacing the innermost evaluation:
=MID(A2,2,FIND("]","[PROGRAMMING]-Old System-TRT Operates-192.168.6.0-qwert8-plain (AMB)")-2)
FIND("]","[PROGRAMMING]-Old System-TRT Operates-192.168.6.0-qwert8-plain (AMB)")
] appears at the 13th position, so this FIND() returns 13. The MID becomes:
=MID(A2,2,13-2) => =MID(A2,2,11)
And if you count the characters in PROGRAMMING, there are 11. I removed 2, because 1 is for the beginning [ to be removed, the second is for the ] to be removed.
Now, it becomes:
=MID("[PROGRAMMING]-Old System-TRT Operates-192.168.6.0-qwert8-plain (AMB)",2,11)
Which means start (including) at character 2 and take 11 characters, which gives the text you are looking for.
The one for () is just as simple if you got the above.
You can use the MID() function if the data always follows the same pattern.
=MID(A1, FIND("(",A1, 1) + 1, LEN(A1)-FIND("(",A1, 1)-1)
Assuming the string is in A1. The first parameter is the string. The second is the start of the substring to extract. You want to start one character past the first parenthesis. The last parameter is the length of the substring to extract. You want to take the whole string minus all the characters before the parenthesis and also ignore the last parenthesis (thus the -1).