I am trying to remove the last trailing underscore(_) from a string using R.
For example,
Col1
TX_
AZ_TX
CA_LX
CHI_
KS_
The above strings should look like
Col1
TX
AZ_TX
CA_LX
CHI
KS
Only the trailing _ be gone. I tried sub("_", "", my_dataframe$my_column)
but this removes all the _ from the string. I am just looking for a function that removes the last trailing _ and not all. Any ideas ?
Trim(char) removes the leading and trailing occurrences of the input character from a string and returns a new string. Each leading and trailing trim operation is stopped when a character other than the input character is encountered.
To remove the underscores from a string, call the replaceAll() method on the string, passing it an underscore as the first parameter, and an empty string as the second, e.g. replaceAll('_', '') . The replaceAll method will return a new string, where all underscores are removed. Copied!
Remove Character from String Python: replace() The replace() method removes the underscore character from the original string and replaces all instances of that character with an empty string.
The deleteCharAt() method accepts a parameter as an index of the character you want to remove. Remove last character of a string using sb. deleteCharAt(str. length() – 1).
You can use sub
(or gsub
) with the regular expression "_$"
to find the _
at the end of the input, then replace with ""
:
s <- c('Col1', 'TX_', 'AZ_TX', 'CA_LX', 'CHI_', 'KS_')
sub("_$","",s)
##[1] "Col1" "TX" "AZ_TX" "CA_LX" "CHI" "KS"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With