This question already has an answer here:
Unexpected empty strings within Python strings
(1 answer)
Closed 3 years ago.
I was just fooling around in the Python console when I noticed these four results of four simple one line statements:
1. "x".endswith("")
True
2. "x".endswith("x")
True
Then I tried to strip the white-spaces from the statement, when they gave me these results:
3. "x".strip().endswith("")
True
4. "x".strip().endswith("x")
True
How can all of the results be True? How can a string function return True for ending with both "x" and ""? Isn't this contradictory or am I missing something here?
Python 2.7 on PyCharm on Windows 10.
If you want to check if a string ends with a space try "x "
For example, "x ".endswith(" ") returns True, but "x ".strip().endswith(" ") returns False.
"" is an empty character, what you are trying to do wont work. The space character is presented like this: " ".
The .strip() function removes all whitespace at the start and end of the string it's called on. Your string, "x", has no whitespace around it, so it will not change in any way (you can check this by running "x" == "x".strip().
You are also checking whether it ends with the empty string, which every string in Python does!
Add some whitespace to your string (eg "x "), and use a whitespace character in your endswith call (eg "x . ".endswith(" ")) to get a good idea of how the strip() function works.
Related
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.
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""
This question already has answers here:
Replacing instances of a character in a string
(17 answers)
Closed 5 years ago.
I tried to replace vowels and add il to them using this code but it didnt work, help!
line=input("What do you want to say?\n")
line = line.replace('e', 'ile')
line = line.replace('o', 'ilo')
line = line.replace('a', 'ila')
line = line.replace('i', 'ili')
line = line.replace('u', 'ilu')
line = line.replace('y', 'ily')
print (line)
But if you type a long sentence it stop working correctly.
could someone please help me?
Want to print "Hello world"
it prints:
Hililellililo wililorld
when should print Hilellilo Wilorld
Try replacing any occurrence of the letters you want with regex. Like this i.e:
import re
re.sub(r'[eE]', 'i$0', "Hello World")
You can replace any letter you want putting them inside the square brackets.
Additionally, that 'i$0' is the literal character 'i' and $0 the letter that was matched.
"Hello world".replace('e', 'ie')
But your question is not very clear, may be you mean something different.
Whenever you do multiple replacements after each other, you always need to be careful with the order in which you do them.
In your case put this replacement first:
line = line.replace('i', 'ili')
Otherwise it replaces the i's in the replacements that have been done before.
When you need to do many replacements it is often better to use an approach that avoids these problems.
One of them can be using regular expressions, as already proposed. Another is scanning the text from start to end for items to replace and replace each item when you find it during the scan and continue scanning after the replacement.
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.
Python 2.7
I was writing code for the PygLatin Translator.
Here's my code:
print"Welcome to the English to Pig Latin translator!"
original=raw_input("Enter a word to translate. Any word.") #Takes an input
if not original=="" or original==" " and original.isalpha()==True: #Checks that 'original' is not an empty text field and also is not a number.
print original #If both conditions are true then prints 'original'
else: #If both conditions don't come out true then prints an error.
print"Either the field is empty or your entry was a number."
If I give 123 as input, it still prints 123, even though it is a number. It is supposed to execute the else block if the input contains numbers. What's the problem with my code? Please explain in simple words as I am only a Python beginner.
Your boolean logic is incorrect; the if statement executes as:
(not original=="") or (original==" " and original.isalpha()==True)
because or has a lower precedence than and (see the documented precedence order).
Because your string is not empty, not original=="" is True, and the second part of the expression isn't even evaluated anymore.
The test can be simplified and made correct with:
if original.strip().isalpha():
because str.isalpha() never is True for empty strings. In the above expression, str.strip() removes all whitespace from the start and the end of the string, leaving an empty string if there was only whitespace in it.
You are printing your input statement, your input statement is original so if you want to print something else replace original in the if statement with what you want to print