Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add spaces in a string [duplicate]

Tags:

python

I am using the python module, markovify. I want to make new words instead of making new sentences.

How can I make a function return an output like this?

spacer('Hello, world!') # Should return 'H e l l o ,   w o r l d !'

I tried the following,

def spacer(text):
  for i in text:
    text = text.replace(i, i + ' ')
  return text

but it returned, 'H e l l o , w o r l d ! ' when I gave, 'Hello, world!'

like image 552
GameStuff Avatar asked Oct 24 '25 17:10

GameStuff


2 Answers

  1. You can use this one.
def spacer(string):
    return ' '.join(string)

print(spacer('Hello,World'))

  1. Or You can change this into.
def spacer(text):
  out = ''
  for i in text:
    out+=i+' '
  return out[:-1]

print(spacer("Hello, World"))
  1. (If you want) You could make the same function into a custom spacer function, But here you also need to pass how many spaces(Default 1) you want in between.
def spacer(string,space=1):
    return (space*' ').join(string)

print(spacer('Hello,World',space=1))
  1. OR FOR CUSTOM SPACES.
 
def spacer(text,space=1):
  out = ''
  for i in text:
    out+=i+' '*space
  return out[:-(space>0) or len(out)]

print(spacer("Hello, World",space=1))

OUTPUT

H e l l o ,   W o r l d
like image 119
Sharim09 Avatar answered Oct 26 '25 06:10

Sharim09


The simplest method is probably

' '.join(string)

Since replace works on every instance of a character, you can do

s = set(string)
if ' ' in s:
    string = string.replace(' ', '  ')
    s.remove(' ')
for c in s:
    string = string.replace(c, c + ' ')
if string:
    string = string[:-1]

The issue with your original attempt is that you have ox2 and lx3 in your string. Replacing all 'l' with 'l ' leads to l . Similarly for o .

like image 37
Mad Physicist Avatar answered Oct 26 '25 07:10

Mad Physicist