I need a simple python code that lets you enter text and shows it with space between each character.
I have made something like this and it works but now I don't know how to make it with spaces
text = input("text: ")
print(f"{text}")
text = input("text: ")
text = ' '.join(list(text))
print(text)
text = input("enter text here")
words=text.split()
output=""
for word in words:
for letter in word:
output = output + letter + " "
print(output)
As mentioned in the comments, you are looking for the join method of a string. It takes an iterable and concatenates it together using the string as separator. As a string is an iterable itself you can simply do
' '.join('Hello')
>>> H e l l o
Related
i have tried this:
mystring=input()
mystring=mystring.split()
for word in mystring:
newword=word[1:]+word[0]
print("".join(newword))
Input:
hello world
the output for the above input:
elloh
orldw
The expected output should be:
elloh orldw
The problem with your current approach is that you are just printing each word once in the loop, which by default is also printing a newline character. You seem to have the idea of populating a new list with the partially reversed version of each word. If so, then define a list and use this approach:
mystring = input()
words = mystring.split()
words_out = []
for word in words:
newword = word[1:] + word[0]
words_out.append(newword)
print(" ".join(words_out))
For an input of hello world, the above script prints:
elloh orldw
You can simply pass a parameter " " to join in order to concatenate the list elements like:
mystring=input()
mystring=mystring.split()
newstring = ' '.join(mystring)
print(newstring)
Try This
myString = "hello world".split()
for word in myString:
new = word[1:]+word[0]
print(new, end=" ", flush=True)
Output:
elloh orldw
Or you can do this:
myString = "hello world".split()
new_word = []
for word in myString:
new = word[1:]+word[0]
new_word.append(new)
print(*new_word, sep=" ")
Output:
elloh orldw
One Line Solution:
print(*[word[1:]+word[0] for word in input().split()], sep=" ")
Input - hello world
Output:elloh orldw
You can change the input.
mystring="hello world"
mystring=[text[1:]+text[0] for text in mystring.split()]
print(" ".join(mystring))
You can code as below for one liner function:
print(" ".join([(word[1:] + word[0]) for word in mystring.strip().split()]))
Basically you were wrong here: print("".join(newword)). It's wrong since the print should be outside the loop, and even if you do that the join function has nothing to join as every time you run the loop the newword variable is assigned with new value and loses the previous value, hence there is nothing to join. So try this bit of code it will definitely help:
mystring=input()
mystring=mystring.split()
final=[]
for word in mystring:
newword=word[1:]+word[0]
final.append(newword)
print(" ".join(final))
I have tried to make this work with a phrase, but I am having issues with getting it to the ie to go at the end of the words. For example HankTIE ouYIE would be the output of the input Thank You.
Here is what I have:
string=input("Please input a word: ")
def silly_encrypter(string):
strr = string.split()
for strr in string:
first_letter_at_the_end = strr[1:] + strr[0]
ie_at_the_end = first_letter_at_the_end + "IE"
print (ie_at_the_end)
silly_encrypter(string)
You can do this:
string=input("Please input a word: ")
def silly_encrypter(string):
splitspace = string.split() # first split the string into spaces.
for s in splitspace: # then looping over each element,
strlist = list(s) # turn the element into a list
strlist.append(strlist[0]) # first number to the last
del strlist[0] # delete the first number
strlist[0] = strlist[0].capitalize() # Capitalize the first letter
strlist.append('IE') # add IE
print(''.join(strlist), end=" ") # join the list
silly_encrypter(string)
Upon reading the accepted answer, I had to provide a cleaner solution:
def silly_encryptor(phrase, suffix="IE"):
new_phrase = []
for word in phrase.split():
new_phrase.append(word[1:]+word[:1]+suffix)
return " ".join(new_phrase)
phrase = input("Please enter your phrase: ")
print (silly_encryptor(phrase))
def cat_latin_word(text):
""" convert the string in another form
"""
constant = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"
for word in text.split():
if word[0] in constant:
word = (str(word)[-1:] + str(word)[:4] + "eeoow")
else:
word = (str(word) + "eeoow")
print(word)
def main():
""" converts"""
text = input("Enter a sentence ")
cat_latin_word(text)
main()
A few pointers:
Converting your code to "one line" doesn't make it better.
No need to type out all consonants, use the string module and use set for O(1) lookup complexity.
Use formatted string literals (Python 3.6+) for more readable and efficient code.
No need to use str on variables which are already strings.
For a single line, you can use a list comprehension with a ternary statement and ' '.join.
Here's a working example:
from string import ascii_lowercase, ascii_uppercase
def cat_latin_word(text):
consonants = (set(ascii_lowercase) | set(ascii_uppercase)) - set('aeiouAEIOU')
print(' '.join([f'{word}eeow' if not word[0] in consonants else \
f'{word[-1:]}{word[:4]}eeoow' for word in text.split()]))
text = input("Enter a sentence ")
cat_latin_word(text)
You may use a list to put all the words or use print() in a different way.
Example:
print(word, end="\t")
where here I use the keyword argument end to set it to '\t' ( by default is '\n')
Simply edited your code to return the results as a words separated by space.
def cat_latin_word(text):
constant = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"
result = []
for word in text.split():
if word[0] in constant:
word = (str(word)[-1:] + str(word)[:4] + "eeoow")
result.append(word)
else:
word = (str(word) + "eeoow")
result.append(word)
return ' '.join(result)
def main():
text = 'ankit jaiswal'
print(cat_latin_word(text))
I have a program that counts and prints all words in a sentence that contains a specific character(ignoring case).
Code in Python -
item=input()
ip=input().tolower()
r=ip.count(item)
print(r)
ip=ip.split()
for word in ip:
if item in word:
print((word), end=' ')
This program works as expected but for the last word that is printed I don't want a white-space after it.
If anyone could guide me on how to remove the space it would be appreciated.
Why don't you use list comprehension and str.join?
print(' '.join([w for w in ip if item in w]))
I don't think there's a way to remove that, as it's a part of your terminal. Best answer I can give you.
I expanded on the code though, cause I was kinda bored.
sentence = input("Enter a sentence: ").lower()
pull = input("Which character(s) do you want to count?: ").lower()
for c in pull:
occurrences = 0
for character in sentence:
if c == character:
occurrences+=1
if c!=" ": print("\'%s\' appears %d times"%(c, occurrences))
for word in sentence.split():
occurrences = 0
for character in word:
if c == character:
occurrences+=1
if occurrences == 1:
print(("1 time in \'%s\'")%(word))
elif occurrences > 0:
print(("%d times in \'%s\'")%(occurrences,word))
+The solution with a list comprehension appears more concise, but if you prefer an alternative you can use the following. It was tested and worked with the example in the picture.
# Amended solution. The commented lines are the amendment.
item = input('Letter: ')
ip = input('Input: ').lower()
r = ip.count(item)
print(r)
ip = ip.split()
outputString = '' # Added: Initialise an empty string to keep the answer
for word in ip:
if item in word:
outputString += word + ' ' # Changed: Accumulates the answer in a string
print(outputString[:-1]) # Added: Prints all the string's characters
# except the last one, which is the additional space
You're close, just change your print statement from print((word), end=' ') to print((word), end=''). Your print statement has a whitespace for the end but you don't want the whitespace so make the end an empty string.
How do I print a specific character from a string in Python? I am still learning and now trying to make a hangman like program. The idea is that the user enters one character, and if it is in the word, the word will be printed with all the undiscovered letters as "-".
I am not asking for a way to make my idea/code of the whole project better, just a way to, as i said, print that one specific character of the string.
print(yourstring[characterposition])
Example
print("foobar"[3])
prints the letter b
EDIT:
mystring = "hello world"
lookingfor = "l"
for c in range(0, len(mystring)):
if mystring[c] == lookingfor:
print(str(c) + " " + mystring[c]);
Outputs:
2 l
3 l
9 l
And more along the lines of hangman:
mystring = "hello world"
lookingfor = "l"
for c in range(0, len(mystring)):
if mystring[c] == lookingfor:
print(mystring[c], end="")
elif mystring[c] == " ":
print(" ", end="")
else:
print("-", end="")
produces
--ll- ---l-
all you need to do is add brackets with the char number to the end of the name of the string you want to print, i.e.
text="hello"
print(text[0])
print(text[2])
print(text[1])
returns:
h
l
e
Well if you know the character you want to search you can use this approach.
i = character looking for
input1 = string
if i in input1:
print(i)
you can change the print statement according to your logic.
name = "premier league"
for x in name:
print(x)
Result shown below:-
To print specific characters of the given string. For example to print 'l' from the given string
name = "premier league"
for x in name:
if x == "l":
print("element found: "+x)