user5675649
user5675649

Reputation: 187

How to remove spaces from string and slice the string into multiple chunks of fixed length

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?

Upvotes: 1

Views: 1069

Answers (2)

Gurupad Hegde
Gurupad Hegde

Reputation: 2155

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.

Upvotes: 1

mmghu
mmghu

Reputation: 621

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"

Upvotes: 2

Related Questions