You can do this with str.ljust(width[, fillchar]):
Return the string left justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than
len(s).
>>> 'hi'.ljust(10)
'hi '
For a flexible method that works even when formatting complicated string, you probably should use the string-formatting mini-language,
using either f-strings
>>> f'{"Hi": <16} StackOverflow!' # Python >= 3.6
'Hi StackOverflow!'
or the str.format() method
>>> '{0: <16} StackOverflow!'.format('Hi') # Python >=2.6
'Hi StackOverflow!'
- 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 .
Is there any string method that checks for spaces? I know isspace() checks for them but it only gives a true if the string only includes white spaces. I'm looking for one that will prince a false if there is any spaces. I'm using these for a project that splices emails so isalpha() wont work cos of that @ and numeric symbols
here is the code
print("Your email may not contain any spaces.")
email = input("Enter your email: ")
index = email.index("@") # this method will return a number
print(index)
username = email[:index]
domain = email[index:]
print(f"your username is {username} and domain is {domain}")