This question already has answers here:
Efficient way to add spaces between characters in a string
(5 answers)
Closed 9 months ago.
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!'
You can use this one.
def spacer(string):
return ' '.join(string)
print(spacer('Hello,World'))
Or You can change this into.
def spacer(text):
out = ''
for i in text:
out+=i+' '
return out[:-1]
print(spacer("Hello, World"))
(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))
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
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 .
The simplest answer to this question would be to use this:-
"Hello world".replace("", " ")[1:-1]
This code reads as follows:-
Replace every empty substring with a space, and then trim off the trailing spaces.
print(" ".join('Hello, world!'))
Output
H e l l o , w o r l d !
Related
def reverse(s):
str = ""
for i in s:
str = i + str
return str
s = "Geeksforgeeks"
print ("The original string is : ",end="")
print (s)
print ("The reversed string(using loops) is : ",end="")
print (reverse(s))
I tried the code in my own way to understand how the above method is reversing the string entered in s in my own way
i will post what i tried to know where I have gone wrong in my understanding
s='preetham'
for i in s:
str=''
s=i+str
print(s)
I tried the above code to just understand what role is i and str playing in helping the code to reverse the string,
as I predicted from my understanding the above code should print the following output
p
r
e
e
t
h
a
m
*
For the output p r e e t h a m you should use :
s='preetham'
str = ''
for i in s:
str=str + i + ' '
print(str)
So, What this does?
First line we store preetham in a variable s.
Second we initialize a variable str with ''[an empty string] to store the new string
Third we start a for loop.
Here what does the for loop do?
The variable i extracts each character[or you may call letter here] of strings one by one and each time executes the code within the loop with each value of i.
Inside the loop:
We append each character[stored in i] of to str along with a space [' '].
Last line outside the loop we print the value of str which is now p r e e t h a m
So What happens when we run the program?
First i = 'p' & str = ''
str = '' + 'p' + ' ' [ = 'p ']
Then i = 'r' & str = 'p '
str = 'p ' + 'r' + ' ' [= 'p r ']
...
Finally i = 'm', & str = 'p r e e t h a '
str = 'p r e e t h a ' + 'm' + ' ' [ = 'p r e e t h a m ']
Lastly in print we print str:
p r e e t h a m
So.
p
r
e
e
t
h
a
m
Will be printed if just use '\n' instead of ' '
Now You can understand the 2 other codes too by this explanation.
I need to select every third letter out of a sentence (starting from the first letter), and print out those letters with spaces in between them.
So it should look like this
Message? cxohawalkldflghemwnsegfaeap
c h a l l e n g e
or
Message? pbaynatnahproarnsm
p y t h o n
I've tried this:
nim = input("Line: ")[::+3]
and it works fine, but I have to keep the spaces between the letters.
Use str.join:
nim = ' '.join(input("Line: ")[::3])
# Line: pbaynatnahproarnsm
print(nim)
Output:
'p y t h o n'
If you want to just print the letters out of sentence with spaces between them, you can use sep= parameter of print() and asterisk *:
print(*input("Line: ")[::3], sep=' ')
Prints:
Line: cxohawalkldflghemwnsegfaeap
c h a l l e n g e
I need a way to copy all of the positions of the spaces of one string to another string that has no spaces.
For example:
string1 = "This is a piece of text"
string2 = "ESTDTDLATPNPZQEPIE"
output = "ESTD TD L ATPNP ZQ EPIE"
Insert characters as appropriate into a placeholder list and concatenate it after using str.join.
it = iter(string2)
output = ''.join(
[next(it) if not c.isspace() else ' ' for c in string1]
)
print(output)
'ESTD TD L ATPNP ZQ EPIE'
This is efficient as it avoids repeated string concatenation.
You need to iterate over the indexes and characters in string1 using enumerate().
On each iteration, if the character is a space, add a space to the output string (note that this is inefficient as you are creating a new object as strings are immutable), otherwise add the character in string2 at that index to the output string.
So that code would look like:
output = ''
si = 0
for i, c in enumerate(string1):
if c == ' ':
si += 1
output += ' '
else:
output += string2[i - si]
However, it would be more efficient to use a very similar method, but with a generator and then str.join. This removes the slow concatenations to the output string:
def chars(s1, s2):
si = 0
for i, c in enumerate(s1):
if c == ' ':
si += 1
yield ' '
else:
yield s2[i - si]
output = ''.join(char(string1, string2))
You can try insert method :
string1 = "This is a piece of text"
string2 = "ESTDTDLATPNPZQEPIE"
string3=list(string2)
for j,i in enumerate(string1):
if i==' ':
string3.insert(j,' ')
print("".join(string3))
outout:
ESTD TD L ATPNP ZQ EPIE
For example
s = "a b c d e f "
Needs to be reduced to
s = "a b c d e f "
Right now I do something like this
for i in xrange(arbitrarilyHighNumber,1,-1):
s = s.replace(" "*i," ")
But I want to make it more dynamic and Pythonic (and assume any number of spaces, too). How can I replace every contiguous space threshold with a single space?
You can use re.sub:
>>> import re
>>> s = "a b c d e f "
>>> re.sub('\s{2,}', ' ', s)
'a b c d e f '
>>>
\s{2,} matches two or more whitespace characters.
Since the regular expression answer has already been given. You could also do it with iterative replacements.
while s.find(" ") is not -1:
s = s.replace(" ", " ")
My original answer of splitting and rejoining gets rid of the leading and trailing whitespaces
' '.join(s.split())
i've been reading from the file and i have hard time getting rid of "\t"
i've tried using i.strip().split("\t")[1] and append it to the list. but if theres more tabs in a row it isnt very useful
for example:
if i do what i described i get
z=['\t\t\t\twoman-in-lingerie', 'newspaper-photo', 'reference-to-marie-antoinette', '\tempty-grave', '\t\t\tbased-on-play', '\t\t\tcanadian-humor', '\t\t\tsitcom', 'hypocrisy', 'stripper']
now i dont know how to remove those tabs, ive been trying to get trough the list and change each element on its own bit it was unsuccessful
If you're just trying to remove tabs you can use this list comprehension:
l2 = [item.strip('\t') for item in l1]
That'll get rid of any leading or trailing tabs on each element.
If you don't want any of the tabs you can use filter after reading everything:
for item in my_list:
item = item.filter(lambda x: x != '\t', item)
The best you can do is use the replace function, replacing tabs ('\t') for empty strings (''):
>>> z = ['\t\t\t\twoman-in-lingerie', '\t\t\tsitcom']
>>> map(lambda x: x.replace('\t',''), z)
['woman-in-lingerie', 'sitcom']
This might give you an idea:
>>> import re
>>> re.sub('\t+','\t', 'hello\t\t\t')
'hello\t'
>>>
z = '''\t\t\t\twoman-in-lingerie
newspaper-photo\t\t\t\t reference-to-marie-antoinette
\tempty-grave
\t\t\tbased-on-play
\t\t\tcanadian-humor\t\t\t
\t\t\tsitcom
hypocrisy\t\t\t\t\tstripper'''
import re
def displ(x):
return '\n'.join(map(repr,x.splitlines(True)))
print displ(z)
print '-------------------------------'
zt = re.sub('\t+',' ',z)
print displ(zt)
print '-------------------------------'
zt = re.sub('(^\t+)|(\t+)',
lambda mat: '' if mat.group(1) else ' ',
z,
flags = re.MULTILINE)
print displ(zt)
print '-------------------------------'
zt = re.sub('(^[ \t]+)|([ \t]+)',
lambda mat: '' if mat.group(1) else ' ',
z,
flags = re.MULTILINE)
print displ(zt)
result
'\t\t\t\twoman-in-lingerie\n'
'newspaper-photo\t\t\t\t reference-to-marie-antoinette\n'
'\tempty-grave\n'
'\t\t\tbased-on-play\n'
'\t\t\tcanadian-humor\t\t\t\n'
'\t\t\tsitcom\n'
'hypocrisy\t\t\t\t\tstripper'
-------------------------------
' woman-in-lingerie\n'
'newspaper-photo reference-to-marie-antoinette\n'
' empty-grave\n'
' based-on-play\n'
' canadian-humor \n'
' sitcom\n'
'hypocrisy stripper'
-------------------------------
'woman-in-lingerie\n'
'newspaper-photo reference-to-marie-antoinette\n'
'empty-grave\n'
'based-on-play\n'
'canadian-humor \n'
'sitcom\n'
'hypocrisy stripper'
-------------------------------
'woman-in-lingerie\n'
'newspaper-photo reference-to-marie-antoinette\n'
'empty-grave\n'
'based-on-play\n'
'canadian-humor \n'
'sitcom\n'
'hypocrisy stripper'
I use the function displ() to display in a manner that shows the escaped characters