1

I have a string which needs to be processed:

  1. Remove all spaces
  2. Group the resulting string in a characters of 5

Currently I have:

new = ''
sym = " !#$%^&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{}~"""
gap = []
for char in text:
    if char in sym or char in gap:
        sym += char
result = []

Anyone knows how?

Gurupad Hegde
  • 2,155
  • 15
  • 30
user5675649
  • 117
  • 1
  • 2
  • 10

2 Answers2

2

You worded your question really confusingly, but if you want to remove all white spaces from a string, you can use replace:

name = "Foo Bar"
name = name.replace(" ","")

print(name) 
# Output: "FooBar"
Gurupad Hegde
  • 2,155
  • 15
  • 30
mmghu
  • 595
  • 4
  • 15
  • but the it needs to be re arranged so the each letter from the string that has the spaces removed are saved in word lengths of 5 – user5675649 Dec 13 '15 at 20:52
  • 3
    Once you have removed the spaces from the string, you can split it by lengths of 5 by using the solution posted by this user: http://stackoverflow.com/questions/13673060/split-string-into-strings-by-length – mmghu Dec 13 '15 at 20:55
1

I am assuming that your string is sym and

  1. You want to remove all spaces from sym
  2. Make a block (list) of words (strings) of length 5.

Python code in steps:

In [1]: sym = " !#$%^&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{}~" #This is your input string

In [2]: sym = sym.replace(" ","") #remove all "" (spaces)

In [3]: sym #Lets check the output
Out[3]: "!#$%^&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{}~"

In [4]: sym_list = [ sym[i:i+5] for i in range(0, len(sym), 5)] # use range to generate iteration with increment 5 each time

In [5]: sym_list #So, did we get blocks of 5 chars? hope so. 
Out[5]: 
['!#$%^',
 "&'()*",
 '+,-./',
 '01234',
 '56789',
 ':;<=>',
 '?@ABC',
 'DEFGH',
 'IJKLM',
 'NOPQR',
 'STUVW',
 'XYZ[\\',
 ']^_`a',
 'bcdef',
 'ghijk',
 'lmnop',
 'qrstu',
 'vwxyz',
 '{}~']

Correct me if any of my assumptions are incorrect.

Gurupad Hegde
  • 2,155
  • 15
  • 30