This is the input given "S H A N N O N B R A D L E Y"
(single space between each letter but 2 space between SHANNON and BRADLEY)
I want output to be in this format (given below)
SHANNON BRADLEY
Any way to do this in R or Python
This is the input given "S H A N N O N B R A D L E Y"
(single space between each letter but 2 space between SHANNON and BRADLEY)
I want output to be in this format (given below)
SHANNON BRADLEY
Any way to do this in R or Python
try this in R
text <- c("S H A N N O N B R A D L E Y")
gsub(" (?! )" , text , replacement = "" , perl = T)
this is another simpler one
gsub("\\b " , text , replacement = "" , perl = T)
If all letters are separated by one space and all words by two, then you could do something like this:
In [2]: "S H A N N O N B R A D L E Y".replace(' ', ' ')[::2]
Out[2]: 'SHANNON BRADLEY'
you can do this in python using :
import re
s = "S H A N N O N B R A D L E Y"
' '.join([''.join(i.split()) for i in re.split(r' {2,}',s)])
Using Python :
import sys
myText="S H A N N O N B R A D L E Y"
for i in range(len(myText)):
if (myText[i]!=" " or myText[i+1]==" "):
sys.stdout.write(myText[i])
else:
pass
Output:
Python implementation:
" ".join(["".join(w.split(" ")) for w in "S H A N N O N B R A D L E Y".split(" ")])
This one-liner would convert it to the required output format.
Explanation: The outer-most split function splits the string into words, the list comprehension reformats them, and the outer-most join re-attaches the words together.
Another option in R
with gsub
:
gsub(" ([^ ])", "\\1", "S H A N N O N B R A D L E Y")
# [1] "SHANNON BRADLEY"
In R:
x <- "S H A N N O N B R A D L E Y"
paste(gsub(' ', '', unlist(strsplit(x, split = ' '))), collapse = ' ')
Python implementation:
import re
re.sub(' (?! )', '', "S H A N N O N B R A D L E Y")
#"SHANNON BRADLEY"
In Python
In [1]: s="S H A N N O N B R A D L E Y"
In [2]: "".join( [i.replace(' ','') if i !='' else i.replace('',' ') for i in s.split(' ') ])
Out[2]: 'SHANNON BRADLEY'