String capitalize with python - python

Now I Am doing very small question at HackRank about string manipulations it is very easy one just like homework dump . The question is turn a given string to capitalize they mentioned their question just like below
You are given a string . Your task is to capitalize each word of S.
Input Format
A single line of input containing the string, S.
Constraints
0< len(s) <1000
The string consists of alphanumeric characters and spaces.
Output Format
Sample Input
hello world
Sample Output
Hello World
I have done here I wrote a two line script from python and I submitted it but
they said it is a wrong answer but I can't understand why is that my code is follow
l=list(map(str.capitalize,input().strip(' ').split()))
print(' '.join(l))
Can anyone tell me what is wrong with my code
(it fails on test cases 1 / 3 / 4 / 5 with Python 3, so )
?

Use str.title
>>>'aba aba'.title()
'Aba Aba'

If you don't specifiy the separator to str.split(), "any whitespace string is a separator and empty strings are removed from the result." Note that here "whitespace" includes tabs, newlines etc.
The problem is not clearly specified (there's no definition of what "word" means) and we don't know what they use for test cases, but I assume they have a couple string with newlines or such. Anyway: explicitely specifying " " as the separator makes the tests pass:
# Python 2
s = raw_input()
print " ".join(x.capitalize() for x in s.strip().split(" "))
# Python 3
s = input()
print(" ".join(x.capitalize() for x in s.strip().split(" ")))

I presume the error is on input(). If HackRank is using python 2.7, this will try to evaluate the input, rather than returning a string. Thus, an input hello world will try to evaluate this string, which is nonsense. If you try raw_input() in stead, this should fix this problem.

Related

How to separate user's input with two separators? And controlling the users input

I want to separate the users input using two different separators which are ":" and ";"
Like the user should input 4 subject and it's amounts. The format should be:
(Subject:amount;Subject:amount;Subject:amount;Subject:amount)
If the input is wrong it should print "Invalid Input "
Here's my code but I can only used one separator and how can I control the users input?
B = input("Enter 4 subjects and amount separated by (;) like Math:90;Science:80:").split(";")
Please help. I can't figure it out.
If you are fine with using regular expressions in python you could use the following code:
import re
output_list = re.split("[;:]", input_string)
Where inside the square brackets you include all the characters (also known as delimiters) that you want to split by, just make sure to keep the quotes around the square brackets as that makes a regex string (what we are using to tell the computer what to split)
Further reading on regex can be found here if you feel like it: https://medium.com/factory-mind/regex-tutorial-a-simple-cheatsheet-by-examples-649dc1c3f285
However, if you want to do it without importing anything you could do this, which is another possible solution (and I would recommend against, but it gets the job done well):
input_string = input_string.replace(";", ":")
output_list = input_string.split(":")
Which works by first replacing all of the semicolons in the input string with colons (it could also work the other way around) and then splitting by the remaining character (in this case the colons)
Hope this helped, as it is my first answer on Stack overflow.

New to Python. Can someone explain this line of code to me?

So i'm new to Python and i'm going through a Python course I purchased and they have a quiz. The last question was to print the last 6 letters of the string. The code is below:
welcome_message = "Hello and welcome to the land of Python"
print(f"The last 6 letters of the welcome message:\n'{welcome_message}'\nare: '{welcome_message[len(welcome_message)-6:]}'")
The output would then be:
The last 6 letters of the welcome message:
'Hello and welcome to the land of Python'
are: Python
This is from the solution. I am not understanding what's going on here: '{welcome_message[len(welcome_message)-6:]}'
I don't understand why the solution included the len() function.
Why can't I just do '{welcome_message[-6:]}'
?
You'll get the same output with this too.
In python -1 index is same as the last index and when its blank it means starting or ending depending on where you put it. for eg.
welcome_message[:]
will print the entire string.
As for your question you can use welcome_message[34:] which instead of counting yourself a better way of writing is welcome_message[len(welcome_message)-6:].
But an even better way of writing is the solution you pointed out, i.e,
welcome_message[-6:]
print(f"The last 6 letters of the welcome message:\n'{welcome_message}'\nare: '{welcome_message[len(welcome_message)-6:]}'")
Here is what is happening welcome_message is a variable which can have infinite letters/character/number/symbols/strings etc.. which the system does not know first hand...
So welcome_message[len...] first finds how many characters are there in the string, not words... I say characters because we supply len() function with the welcome_message variable which has just 1 string... so thus far i hope I explained what happened till
{welcome_message[len(welcome_message)]} and then its just plain old -6 arithmetic operation from the count that is returned by the len() fn
welcome_message = "Hello and welcome to the land of Python"
print(f"The last 6 letters of the welcome message:\n'{welcome_message}'\nare: '{welcome_message[len(welcome_message)-6:]}'")
Here welcome_message is storing a string which is "Hello and welcome to the land of Python".
while printing if we will add \n in a string it will output a newline in answer.
len(welcome_message)-6 = 39-6 = 33.
in string slicing s[i:] it will give output as a string which includes the character from i to end of the string.
Hence welcome_message[len(welcome_message)-6:] will output the characters from index of 33 to 39th index.
Remember that " " is also a character of the string.

How do you input escape sequences in Python? [duplicate]

This question already has answers here:
Process escape sequences in a string in Python
(8 answers)
Closed 7 months ago.
Say you make the following program
a=input("Input: ")
print(a)
and try to input the newline character, \n:
Input: a\nb
a\nb
The input has not been treated as the \n character but rather as two separate characters, \\ and n. How do you get an input with an escape sequence to be treated as an escape sequence? The result for the sample above should be
Input: a\nb
a
b
The input statement takes the input that the user typed literally. The \-escaping convention is something that happens in Python string literals: it is not a universal convention that applies to data stored in variables. If it were, then you could never store in a string variable the two characters \ followed by n because they would be interpreted as ASCII 13.
You can do what you want this way:
import ast
import shlex
a=input("Input: ")
print(ast.literal_eval(shlex.quote(a)))
If in response to the Input: prompt you type one\ntwo, then this code will print
one
two
This works by turning the contents of a which is one\ntwo back into a quoted string that looks like "one\ntwo" and then evaluating it as if it were a string literal. That brings the \-escaping convention back into play.
But it is very roundabout. Are you sure you want users of your program feeding it control characters?
You can replace \\n with \n to get the result you want:
a = a.replace('\\n', '\n')
input won't read \ as an escape character.
If you are just interested in printing the input, you can use something like this, which will handle other escape characters. It's not an ideal solution in my opinion and also suffers from breaking with '.
eval('print("{}")'.format(a))
Hi you can't input \n as it would result in the input closing. Here is what you can try :
use replace to post-process the string
input().replace("\\n", "\n")
use while to input until you get an empty line
inputs = []
current = input()
while current:
inputs.append(current)
current = input()
"\n".join(inputs)
Python can do this natively:
text = r"Hello\nworld!"
text = text.encode().decode( "unicode_escape" )
print( text )
Note that your shell's (shlex) escaping - if any - may differ from Python's own escape protocol, which is used for parsing the strings in user code.

Output of print("""Hello World's"s""""") in python 3.6 [duplicate]

This question already has answers here:
String concatenation without '+' operator
(6 answers)
Closed 4 years ago.
I read that anything between triple quotes inside print is treated literal so tried messing things a little bit. Now I am not able to get above statement working. I searched internet but could not find anything.
statement:
print("""Hello World's"s""""")
Output I am getting:
Hello World's"s
Expected output:
Hello World's"s""
print("""Hello World's"s""""") is seen as print("""Hello World's"s""" "") because when python find """ it automatically ends the previous string beginning with a triple double-quote.
Try this:
>>> print("a"'b')
ab
So basically your '"""Hello World's"s"""""' is just <str1>Hello World's"s</str1><str2></str2> with str2 an empty string.
Triple quoted string is usually used for doc-string.
As #zimdero pointed out Triple-double quote v.s. Double quote
You can also read https://stackoverflow.com/a/19479874/1768843
And https://www.python.org/dev/peps/pep-0257/
If you really want to get the result you want just use \" or just you can do combination with ``, .format() etc
print("Hello World's\"s\"\"")
https://repl.it/repls/ThatQuarrelsomeSupercollider
Triple quotes within a triple-quoted string must still be escaped for the same reason a single quote within a single quoted string must be escaped: The string parsing ends as soon as python sees it. As mentioned, once tokenized your string is equivalent to
"""Hello World's"s""" ""
That is, two strings which are then concatenated by the compiler. Triple quoted strings can include newlines. Your example is similar to
duke = """Thou seest we are not all alone unhappy:
This wide and universal theatre
Presents more woeful pageants than the scene
Wherein we play in."""
jaques = """All the world's a stage,
And all the men and women merely players:
They have their exits and their entrances;
And one man in his time plays many parts."""
If python was looking for the outermost triple quotes it would only have defined one string here.
Simple with ''' to not complicate things:
print('''Hello World's"s""''')
Maybe this is what you are looking for?
print("\"\"Hello World's's\"\"")
Output:
""Hello World's's""

"ValueError: invalid literal for int() with base 10" trying to get character's ASCII code

I am a beginner in python. I came across this question in codewars.
Jaden is known for some of his philosophy that he delivers via Twitter. When writing on Twitter, he is known for almost always capitalizing every word.
Your task is to convert strings to how they would be written by Jaden Smith. The strings are actual quotes from Jaden Smith, but they are not capitalized in the same way he originally typed them.
Example :
Not Jaden-Cased: "How can mirrors be real if our eyes aren't real"
Jaden-Cased: "How Can Mirrors Be Real If Our Eyes Aren't Real"
This is my attempt (I am supposed to code using a function)
def toJadenCase(string):
l = len(string)
for i in range(0,l):
if string[i] == ' ':
y = string[i]
string[i+1] = chr(int(y)-32)
return srting
s = raw_input()
print toJadenCase(s)
When run, the following errors showed up
How can mirrors be real if our eyes aren't real (this is the input string)
Traceback (most recent call last):
File "jaden_smith.py", line 9, in <module>
print toJadenCase(s)
File "jaden_smith.py", line 6, in toJadenCase
string[i+1] = chr(int(y)-32)
ValueError: invalid literal for int() with base 10: ''
I couldn't understand these errors even after google-ing it. Any help would be appreciated. I would also be great if other errors in my code are highlighted and a better code is suggested.
Thanks in advance :D
As Goodies points out, string should not be used as a variable name
Following the Zen of Python, this is technically a function that does exactly what you're trying to achieve:
def toJadenCase(quote):
return quote.title()
Edit:
Revised version to deal with apostrophes:
import string
def toJadenCase(quote):
return string.capwords(quote)
First you have to understand that strings are immutable, so you cannot set a single character inside a string, but build a new string from the old one and replace the old one (this can be usually done still in one pass so it's not a big complication).
Second, for most of these kind of operations, it is much better to use the methods of the string object itself, rather than redo everything from scratch.
Said that, there is still some complication with the question, but a function that does what you want is in the module string:
import string
s="How can mirrors be real if our eyes aren't real"
newstring=string.capwords(s)
If you prefer (why?!) a DIY solution (using string methods):
newstring=' '.join([ss.capitalize() for ss in s.split()])
Note that using split without argument splits the string on any whitespace (e.g. tabs etc.), that I think is the desired behavior.
If you want to do this without using a function that already exists, this is how I would do it and I'll explain everything:
Assuming you get a string with ONLY text based words and all words start with a character*
def toJadenCase(string):
words = string.strip().split()
# This first strips all empty spaces around the words in the text and then splits the string by spaces (default) otherwise you can add a character inside split in order to split it at the character. This returns a list of words in the sentence.
li = [] # initialize empty list
for word in words:
word = chr(ord(word[0])-32) + word[1:]
# So there's a couple of things going on here.
# I could use .upper() to upper case something (like word[0].upper() + word[1:]
# in order to get it but I wanted to do it without the use of that.
# That being said, ord just figures out the ascii number and subtracting
# 32 makes it uppercase. chr changes it back to a string.
# Then it can be concatenated to the rest of the word.
# Strings can be treated as lists in python so word[0] and word[1:] works
Also, word[1:] just means from the 1st index to the end.
li.append(word) # this appends the word to the list
return ' '.join(li) # this joins all of the words in the list with a space
Now, if you want something a lot more concise (you can use .capitalize()):
def toJadenCaseShort(string):
return ' '.join([x.capitalize() for x in string.strip().split()])
which returns:
>>> abc("hello my friends")
'Hello My Friends'
Basically what it does is it uses list comprehension to strip and then split the words, capitalizes them, and then joins them with spaces!
Of course, you could just use string.title() as mark s. says but what's the fun in that? :)
Here is the answer that passed for me
import string
def toJadenCase(str):
quote = string.capwords(str)
return quote #Do not use print(quote) as it adds spaces
def toJadenCase(str):
quote = string.capwords(str)
return quote #Do not use print(quote) as it adds spaces

Categories