Combining `expression()` with `\n`
As @otsaw said in his answer to your earlier question, plotmath
(and therefore expression
) doesn't allow linebreaks.
However, as a hack, you can use atop
to let ≥80
appears on top of (N=10)
. But as you will soon see it doesn't match with the other labels:
labs <- c("0-9\n(N=10)","10-29\n(N=10)","30-49\n(N=10)",
"50-64\n(N=10)","65-79\n(N=10)",
expression(atop(phantom(x) >=80, (N==10))))
So, as a further hack, you can pass the other labels as expressions:
labs <- c(expression(atop(0-9,(N==10))),expression(atop(10-29,(N==10))),
expression(atop(30-49,(N==10))), expression(atop(50-64,(N==10))),
expression(atop(65-79,(N==10))), expression(atop(phantom(x) >=80, (N==10))))
But of course you have @otsaw solution (using Unicode) that is considerably less wordy:
labs <- c("0-9\n(N=10)","10-29\n(N=10)","30-49\n(N=10)",
"50-64\n(N=10)","65-79\n(N=10)",
"\u2265 80\n(N=10)")
How to combine N amount of expression trees with OR/And operators
This shall be simple, just use Expression.And
or Expression.Or
calls to aggregate various expressions in the single Expression tree call. Let me provide an example, if you have a List<Expression>
, which needs to be aggreagated into Single Expression then use the following code using And
aggregation for example, it can be any of the predicate builder:
List<Expression> exptree = new List<Expression>();
var resultEXpression = exptree.Skip(1).Aggregate(exptree.FirstOrDefault(),
(exp1,exp2) => Expression.And(exp1,exp2));
This is just a sample, there are lot of Expression builders available by default, which can help bind the expressions together based on relevant logic, it can be Or, AndAlso, OrAssign, OrElse
Split text with '\r\n'
The problem is not with the splitting but rather with the WriteLine
. A \n
in a string printed with WriteLine
will produce an "extra" line.
Example
var text =
"somet interesting text\n" +
"some text that should be in the same line\r\n" +
"some text should be in another line";
string[] stringSeparators = new string[] { "\r\n" };
string[] lines = text.Split(stringSeparators, StringSplitOptions.None);
Console.WriteLine("Nr. Of items in list: " + lines.Length); // 2 lines
foreach (string s in lines)
{
Console.WriteLine(s); //But will print 3 lines in total.
}
To fix the problem remove \n
before you print the string.
Console.WriteLine(s.Replace("\n", ""));
Expression and new line in plot labels
You can introduce a line break inside an expression:
bquote(atop("first line",
"second line" ~ x ^ 2))
(I’m using bquote
rather than expression
here – both work in this case.)
Execute demo(plotmath)
for more information and look at the documentation for atop
.
boxplot
apparently has some trouble interpreting expressions in its title. A simple fix is to plot the title separately:
boxplot(data, main = '')
title(bquote(atop("first line", "second line" ~ x ^ 2)))
How to use newline '\n' in f-string to format output in Python 3.6?
You can't. Backslashes cannot appear inside the curly braces {}
; doing so results in a SyntaxError
:
>>> f'{\}'
SyntaxError: f-string expression part cannot include a backslash
This is specified in the PEP for f-strings:
Backslashes may not appear inside the expression portions of f-strings, [...]
One option is assinging '\n'
to a name and then .join
on that inside the f
-string; that is, without using a literal:
names = ['Adam', 'Bob', 'Cyril']
nl = '\n'
text = f"Winners are:{nl}{nl.join(names)}"
print(text)
Results in:
Winners are:
Adam
Bob
Cyril
Another option, as specified by @wim, is to use chr(10)
to get \n
returned and then join there. f"Winners are:\n{chr(10).join(names)}"
Yet another, of course, is to '\n'.join
beforehand and then add the name accordingly:
n = "\n".join(names)
text = f"Winners are:\n{n}"
which results in the same output.
Note:
This is one of the small differences between f
-strings and str.format
. In the latter, you can always use punctuation granted that a corresponding wacky dict is unpacked that contains those keys:
>>> "{\\} {*}".format(**{"\\": 'Hello', "*": 'World!'})
"Hello World!"
(Please don't do this.)
In the former, punctuation isn't allowed because you can't have identifiers that use them.
Aside: I would definitely opt for print
or format
, as the other answers suggest as an alternative. The options I've given only apply if you must for some reason use f-strings.
Just because something is new, doesn't mean you should try and do everything with it ;-)
How to combine lines in regular expressions?
The (.*?)\n(.*?)
pattern will never work well because the (.*?)
at the end of the pattern will always return an empty string (since *?
is a lazy matching quantifier and if it can return zero characters (and it can) it will. Use greedy matching and adjust the pattern like:
(.+)\r?\n *(.*)
or - since SublimeText uses Boost regex - you can match any newline sequence with \R
:
(.+)\R *(.*)
and replace with \1\t\2
. Note I replaced *?
with +
in the first capturing group because you need to match non-empty lines.
Regex breakdown:
(.+)
- one or more characters other than a newline (as many as possible) up to\R
- a newline sequence (\r\n
,\r
or just\n
)*
- a literal space, zero or more occurrences(.*)
- Group 2: zero or more characters other than a newline (as many as possible)
/
Python Combining f-string with r-string and curly braces in regex
You can use this string to combine the n
value into your regexp, using double curly brackets to create a single one in the output:
fr'(?=(\S{{{n}}}))'
The regex needs to have {}
to make a quantifier (as you had in your original regex {4}
). However f
strings use {}
to indicate an expression replacement so you need to "escape" the {}
required by the regex in the f string. That is done by using {{
and }}
which in the output create {
and }
. So {{{n}}}
(where n=4
) generates '{' + '4' + '}' = '{4}'
as required.
Complete code:
import re
def ngram_finder(x, n):
pat = fr'(?=(\S{{{n}}}))'
return re.findall(pat, x)
x = 'abcdef'
print(ngram_finder(x, 4))
print(ngram_finder(x, 5))
Output:
['abcd', 'bcde', 'cdef']
['abcde', 'bcdef']
Related Topics
Replace Duplicated Elements with Na, Instead of Removing Them
Set Ggplot Plots to Have Same X-Axis Width and Same Space Between Dot Plot Rows
How to Export S3 Method So It Is Available in Namespace
Setting Upper and Lower Limits in Rnorm
How to Apply Cross-Hatching to a Polygon Using the Grid Graphical System
Read/Write Data in Libsvm Format
Subsetting a Dataframe for a Specified Month and Year
Use R Code or Windows User Variable ("%Userprofile%") in Yaml
Converting Factors to Binary in R
Calculate Group Mean While Excluding Current Observation Using Dplyr
Dt: Dynamically Change Column Values Based on Selectinput from Another Column in R Shiny App
Creating a Density Histogram in Ggplot2
Connect to Postgres via Ssl Using R
R- How to Dynamically Name Data Frames
Merge Data.Frames Based on Year and Fill in Missing Values