Capitalizing words in (Python)? [duplicate] - python

This question already has answers here:
Why doesn't calling a string method (such as .replace or .strip) modify (mutate) the string?
(3 answers)
Closed 6 years ago.
I was trying to write something to capitalize each word in a sentence. And it works fine, as follows:
print " ".join((word.capitalize() for word in raw_input().strip().split(" ")))
If the input is 'hello world', the output would be :
Hello World
But I tried writing it differently as follows :
s = raw_input().strip().split(' ')
for word in s:
word.capitalize()
print ' '.join(s)
And its output would be wrong :
hello world
So what's wrong with that, why the result isn't the same ?! Thank you.

The problem in your code is that strings are immutable and you are trying to mutate it. So if you wont to work with loop you have to create new variable.
s = raw_input().strip().split(' ')
new_s = ''
for word in s:
new_s += s.capitalize()
print new_s
Or, It would work if you use enumerate to iterate over list and update s:
s = raw_input().strip().split(' ')
for index, word in enumerate(s):
s[index] = .capitalize()
print ' '.join(s)
But the best way to capitalize words in string is to use str.title() - method for capitalization of words in string:
s = 'hello word'
print(s.title())

print ' '.join([i.capitalize() for i in raw_input('Enter text here:').split(' ')])
This will solve you problem.

Strings are immutable and you are trying to update the same value which is not poassible.
Create a new string and update in that way.
s = raw_input().strip().split(' ')
st = ''
for word in s:
st+= word.replace(word,word.capitalize())
print ''.join(st)
Or
print " ".join([i.capitalize() for i in raw_input().strip().split(" ")])

Related

Wrong output in function

Hi I'am totally new to programmering and i have just jumped into it.
The problem i am trying to solve is to make a function that standardized an adress as input.
example:
def standardize_address(a):
numbers =[]
letters = []
a.replace('_', ' ')
for word in a.split():
if word. isdigit():
numbers. append(int(word))
elif word.isalpha():
letters.append(word)
s = f"{numbers} {letters}"
return s
Can someone help me explain my error and give me a "pro" programmers solution and "noob" (myself) solution?
This is what i should print:
a = 'New_York 10001'
s = standardize_address(a)
print(s)
and the output should be:
10001 New York
Right now my output is:
[10001] ['New', 'York']
Issues
strings are immutable so you need to keep the replace result, so do a = a.replace('_', ' ') or chain it before the split call
You need to concatenate the lists into one numbers + letters then join the elements with " ".join()
don't convert the numeric to int, that's useless and would force you to convert them back to str in the " ".join
def standardize_address(a):
numbers = []
letters = []
for word in a.replace('_', ' ').split():
if word.isdigit():
numbers.append(word)
elif word.isalpha():
letters.append(word)
return ' '.join(numbers + letters)
Improve
In fact you want to sort the words regarding the isdigit condition, so you can express that with a sort and the appropriate sorted
def standardize_address(value):
return ' '.join(sorted(value.replace('_', ' ').split(),
key=str.isdigit, reverse=True))
numbers and letters are both lists of strings, and if you format them they'll be rendered with []s and ''s appropriately. What you want to do is to replace this:
s = f"{numbers} {letters}"
return s
with this:
return ' '.join(numbers + letters)
numbers + letters is the combined list of number-strings and letter-strings, and ' '.join() takes that list and turns it into a string by putting ' ' between each item.

How can I replace every letter in a string with something else? (Python 3) [duplicate]

This question already has answers here:
replace all characters in a string with asterisks
(4 answers)
Closed 2 years ago.
I have to develop a hangman game as part of a school assignment, and I'm trying to create a new string that will output the word to be guessed as just stars. e.g hello would be ****. Below is the code I have tried, the output seems to be only the last letter of the string to be replaced with a star, but the rest of the string is seemingly untouched:
word_to_guess = input("Enter a word for player 2 to guess:")
def guess_the_word(word_to_guess):
for letter in word_to_guess:
number_of_letters = word_to_guess.replace(letter, '*') #Taking the original string and replacing each letter with a star, giving player 2 an indicator of how many letters there are to guess
print("{} is the word for today".format(number_of_letters))
Any pointers as to where I went wrong will be appreciated
Just try
'*' * len(word_to_guess)
which will multiply the * with the length of word_to_guess.
You are reassigning the output of word_to_guess.replace, so each time it's for a single operation:
word = 'hello'
output = word.replace('h', '*')
# *ello
output = word.replace('e', '*')
# h*llo
# and so on
You probably just need
def guess_the_word(word):
letters = ''
for char in word:
letters += '*'
print(letters)
Or
def word_to_guess(word):
return ''.join('*' for char in word)
A better way to get a hashed version the same length as the word may be by using the length property.
Example:
word = "sponge"
hashedWord = ''
hashedWord += '#'*len(word)
print(f"Hashed word: {hashedWord}")
Output:
Hashed word: ######

Space between each character in python

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

How can i join words in an array to form a single line sentence without it spanning to a new line

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))

Python: How to print results from conditions all in one line [duplicate]

This question already has answers here:
How can I print multiple things on the same line, one at a time?
(18 answers)
Closed last month.
I'm new to coding, and I found this exercise problem in a Python practice website. The instructions go like this:
"Write a function translate() that will translate a text into "rövarspråket" (Swedish for "robber's language"). That is, double every consonant and place an occurrence of "o" in between. For example, translate("this is fun") should return the string "tothohisos isos fofunon".
So I inputted this code:
def translate(string):
vowels=['a','e','i','o','u']
for letter in string:
if letter in vowels:
print(letter)
else:
print(letter+'o'+letter)
print(translate('this is fun'))
and I got this:
tot
hoh
i
sos
o
i
sos
o
fof
u
non
None
So how do I put all these strings in one line? I've been scratching my head for so long. Please help and thank you:)
You can concatenate the strings iteratively. You should include a whitespace as part of the characters to exclude to avoid putting an 'o' in between whitespaces.
def translate(string):
notconsonant = ['a','e','i','o','u', ' ']
s = ''
for letter in string:
if letter in notconsonant:
s += letter
else:
s += letter+'o'+letter
return s
Or use join with a generator expression that returns the right letter combination via a ternary operator:
def translate(string):
notconsonant = {'a','e','i','o','u', ' '}
return ''.join(letter if letter in notconsonant else letter+'o'+letter for letter in string)
Note that you can speed up the lookup of letters that are not consonants if you made the list a set, as membership check for sets is relatively faster.
>>> translate('this is fun')
'tothohisos isos fofunon'
Just use the end parameter in print function. (I assumed that you are using python 3.x, with print being a function)
def translate(string):
vowels=['a','e','i','o','u']
for letter in string:
if letter in vowels:
print(letter, end='')
else:
print(letter+'o'+letter, end='')
print(translate('this is fun'))
Try to append it in a temporary string and to print it at the end ;)
print get's you to a new line. Use a concatenation and a new string instead (here the new string is called result) :
def translate(string):
vowels=['a','e','i','o','u']
# Use a new variable :
result = ''
for letter in string:
if letter in vowels:
result = result + letter
else:
result = result + letter + 'o' + letter
return result
print(translate('this is fun'))

Categories

Resources