4

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

Utsav Bhargava
  • 121
  • 2
  • 11

9 Answers9

9

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)
Nader Hisham
  • 5,214
  • 4
  • 19
  • 35
5

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'
Blender
  • 289,723
  • 53
  • 439
  • 496
2

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)])
sachin saxena
  • 926
  • 5
  • 18
2

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:

enter image description here

Ebrahim Ghasemi
  • 5,850
  • 10
  • 52
  • 113
2

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.

ssundarraj
  • 809
  • 7
  • 16
1

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"
Cath
  • 23,906
  • 5
  • 52
  • 86
0

In R:

x <- "S H A N N O N     B R A D L E Y"
paste(gsub(' ', '', unlist(strsplit(x, split = '     '))), collapse = ' ')
Tomas Greif
  • 21,685
  • 23
  • 106
  • 155
0

Python implementation:

import re
re.sub(' (?! )', '', "S H A N N O N  B R A D L E Y")
#"SHANNON BRADLEY"
Matt
  • 17,290
  • 7
  • 57
  • 71
0

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'
Ajay
  • 5,267
  • 2
  • 23
  • 30