Print Backslash in R Strings

print backslash in R strings

You should use cat.

bib <- "\\cite"
cat(bib)
# \cite

You can remove the ## and [1] by setting a few options in knitr. Here is an example chunk:

<<newChunk,echo=FALSE,comment=NA,background=NA>>=
bib <- "\\cite"
cat(bib)
@

which gets you \cite. Note as well that you can set these options globally.

How to escape backslashes in R string

[...] If I want to get a string containing 5 \ ,should i write 10 \ [...]

Yes, you should. To write a single \ in a string, you write it as "\\".

This is because the \ is a special character, reserved to escape the character that follows it. (Perhaps you recognize \n as newline.) It's also useful if you want to write a string containing a single ". You write it as "\"".

The reason why \\\str is invalid, is because it's interpreted as \\ (which corresponds to a single \) followed by \s, which is not valid, since "escaped s" has no meaning.

Adding a single backslash (\) to a string in R

why are you jumping fomr one "\" to 4 "\"?

> try2 = gsub("%","\\%",try,fixed = TRUE)
> try2
[1] "0\\% success"

This should be read as "\\", which (as far as i know) the regular expression will understand as an "\".

I hope i understood you right- and this is a possible sulution for you!

substitute single backslash in R

When you need to use a backslash in the string in R, you need to put double backslash. Also, when you use gsub("\\", "/", str), the first argument is parsed as a regex, and it is not valid as it only contains a single literal backslash that must escape something. In fact, you need to make gsub treat it as a plain text with fixed=TRUE.

However, you might want to use normalizePath, see this SO thread.

How do I write a string with absolutely ONE backslash in a text file using R?

If you use the double backslash in the code, it will print a single backslash in the file:

txtf <- "file.txt"
file <- file(txtf)
writeLines(paste0(' C:\\PROGRA~2'), file)
close(file)

Sample Image

How to escape a backslash in R?

I found a solution that works

str = gsub("([\\])","", str)

R how to output \ in sprintf

Not sure what you're using it for but the \\ will work if you're trying to use it in a .Rnw file for instance but R needs the \\. If you just want to cut and paste it somewhere wrap it with cat as in: cat(sprintf("& $\\pm %s \\delta$", 1.23))

String replace character with backslash and double quote in a column of an R dataframe

I think in R, they will always print two backslashes together if one of them are escaped. When two backslashes are shown together, it is only a syntax to show that these should be interpreted as a character "\" but not an escape character.

To confirm that, you can try to save your dataframe to a text file, you will see that there's actually only one backslash in the string.

df <- df %>% mutate(option_json = gsub(" inches", '\\\\"', option_json, ignore.case = T) %>% 
gsub(" Feet", "\\'", ., ignore.case = T))

write.table(df, "df.tsv", quote = F, row.names = F)

Output copied from "df.tsv"

ID option_json
1 {"thickness":"0.031\"","tensile strength":"600 lb","size":"0.5\" x 7200'"}
2 {"thickness":"0.031\"","tensile strength":"600 lb","size":"0.5\" x 7200'"}
3 {"tensile strength":"600 lb","color":"Black","size":"0.5\" x 7200'"}

Try printing the "option_json" column

You can see that before every double quote " character, there is a escape character \. And \\ is used to indicate a single \ character.

print(df$option_json)
[1] "{\"thickness\":\"0.031\\\"\",\"tensile strength\":\"600 lb\",\"size\":\"0.5\\\" x 7200'\"}"
[2] "{\"thickness\":\"0.031\\\"\",\"tensile strength\":\"600 lb\",\"size\":\"0.5\\\" x 7200'\"}"
[3] "{\"tensile strength\":\"600 lb\",\"color\":\"Black\",\"size\":\"0.5\\\" x 7200'\"}"

How to print a single backslash in python in a string?

In IDLE (Python's Integrated Development and Learning Environment), expression values have their representation echoed to stdout.

As https://docs.python.org/3/library/idle.html explains:

The repr function is used for interactive echo of expression values.
It returns an altered version of the input string in which control
codes, some BMP codepoints, and all non-BMP codepoints are replaced
with escape codes.

If you want to print a string, use the print() function. Otherwise you'll get its representation.

Consider the following code entered into IDLE:

>>> hitman_str = "Agent \ 47"
>>> print(hitman_str) # We see only one slash when using print
Agent \ 47
>>> hitman_str # This shows the representation, which shows two slashes
'Agent \\ 47'
>>> print(repr(hitman_str)) # Same as above
'Agent \\ 47'

There are multiple ways to get a string with only one slash:

single_slash1 = "\\"
>>> print(single_slash1)
\
>>> single_slash2 = "\ "[0]
>>> print(single_slash2)
\
>>> single_slash1 == single_slash2
True

Similarly, there are multiple ways to get a string with two consecutive slashes:

>>> two_slashes1 = "\\\\"
>>> print(two_slashes1)
\\
>>> print(repr(two_slashes1))
'\\\\'
>>> two_slashes1
'\\\\'
>>> len(two_slashes1)
2
>>> two_slashes2 = r"\\"
>>> print(two_slashes2)
\\
>>> print(repr(two_slashes2))
'\\\\'
>>> two_slashes2
'\\\\'
>>> len(two_slashes2)
2

We can confirm hitman_str only has one slash:

>>> hitman_str.count(single_slash1)
1

We can iterate through the string and print each character and its Unicode code point.
As expected, this shows only one slash:

>>> for char in hitman_str:
print(char, ord(char))

A 65
g 103
e 101
n 110
t 116
32
\ 92
32
4 52
7 55

Raw strings are very handy, especially for Windows paths if you don't wanna use os.path or pathlib:

>>> filename = r"C:\Users\Lee Hong\Documents\New Letters\Impatient 1999-06-14.txt" # Works fine
>>> filename = "C:\Users\Lee Hong\Documents\New Letters\Impatient 1999-06-14.txt" # Error
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
>>> raw_str = r"This \\\has \11 \\slashes \\and \no \line \break"
>>> print(raw_str)
This \\\has \11 \\slashes \\and \no \line \break
>>> raw_str.count(single_slash1)
11

For more information, including a list of escape sequences to watch out for, refer to https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals

Extract text before backslash in R

We may use str_remove to match the \\ and remove the rest

library(stringr)
str_remove(str1, "\\\\.*")
[1] "Charlie Blackmon" "Freddie Freeman"

If we use in tidyverse syntax

library(dplyr)
df1 <- df1 %>%
mutate(Player = str_remove(Player, "\\\\.*"))

-output

df1
# A tibble: 4 × 5
Player TOB TB G WAR
<chr> <dbl> <dbl> <dbl> <dbl>
1 Joey Votto 321 323 162 8.1
2 Juan Soto 304 268 151 7.1
3 Charlie Blackmon 288 387 159 5.5
4 Freddie Freeman 274 312 162 5.5

Or using base R with trimws

 trimws(df1$Player, whitespace = "\\\\.*")
[1] "Joey Votto" "Juan Soto" "Charlie Blackmon" "Freddie Freeman"

data

str1 <- c("Charlie Blackmon\\blackch02", "Freddie Freeman\\freemfr01")


Related Topics



Leave a reply



Submit