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.
Related
Write a method to replace all spaces in a string with '%20'. You may assume that the string
has sufficient space at the end to hold the additional characters, and that you are given the "true" length of the string.
This is how I tried to solve, but I know I haven't addressed the question correctly where author asks us to assume the additional space at the end and the true length of the string. I am a beginner in programming trying to learn Algorithms and DS, quite a head bagging on this side.
def replace(astring):
alist= list(astring)
for i in range(len(alist)):
if alist[i] == ' ':
alist[i]= '%20'
return (''.join(alist))
print(replace("Mr John Smith "))
Since you are trying to learn algorithms, I think it will be beneficial to leave two hints to help you forward instead of the answer
"Mr John Smith ".rstrip() will strip any space at the end of a string. This means you will not have to worry about any logic for whitespace
Even though the solution works, you are using extra space by creating alist. Maybe try replacing things in the string itself? In Python a string can already by accessed as a string. For example astring[:2] is valid. Also 'hello world!'.replace(' ', 'test') is your friend
You can use the following code :
import urllib.parse
urllib.parse.quote("Mr John Smith ")
I need to create a box with parameters that prints any input the user puts in. I figured that the box should be the length of the string, but I'm stuck with empty code, because I don't know where to start.
It should look like this:
I agree with Daniel Goldfarb comments. Don't look for help without trying.
If you still couldn't get how to do that, then only read my remaining comment.
Just print :
str = string entered
len(str) = string length
+-(len(str) * '-')-+
| str |
+-(len(str) * '-')-+
So hopefully you can learn, don't want to just write the code for you. Basically break it into steps. First you need to accept user input. If you don't know how to do that, try googling, "python accept user input from stdin" or here is one of the results from that search: https://www.pythonforbeginners.com/basics/getting-user-input-from-the-keyboard
Then, as you mentioned, you need the length of the string that was input. You can get that with the len function. Then do the math: It looks like you want "|" and two spaces on each side of the string, giving the length plus 6 ("| " on either side). This new length is what you should make the "+---+" strings. Use the print() function to print out each line. I really don't want to say much more than that because you should exercise your brain to figure it out. If you have a question on how to generate "+---+" of the appropriate length (appropriate number of "-" characters) you can use string concatenation and a loop, or just use the python string constructor (hint: google "construct python string of len repeat characters"). HTH.
One more thing, after looking at your code, in addition to my comment about printing the string itself within the box, I see some minor logic errors in your code (for example, why are you subtracting 2 from the width). THE POINT i want to me here is, if you ware going to break this into multiple small functions (a bit overkill here, but definitely a good idea if you are just learning as it teaches you an important skill) then YOU SHOULD TEST EACH FUNCTION individually to make sure it does what you think and expect it to do. I think you will see your logic errors that way.
Here is the solution, but I recommend to try it out by yourself, breakdown the problem into smaller pieces and start from there.
def format(word):
#It declares all the necessary variables
borders =[]
result = []
# First part of the result--> it gives the two spaces and the "wall"
result.append("| ")
# Second part of the result (the word)
for letter in word:
result.append(letter)
# Third part of the result--> Ends the format
result.append(" |")
#Transforms the list to a string
result = "".join(result)
borders.append("+")
borders.append("--"+"-"*len(word)+"--")
borders.append("+")
borders="".join(borders)
print(borders)
print(result)
print(borders)
sentence = input("Enter a word: ")
format(sentence)
I'm new to Python, and I've found this solution. Maybe is not the best solution, but it works!
test = input()
print("+-", end='')
for i in test:
print("-", end='')
print("-+")
print("| " + test + " |")
print("+-", end='')
for i in test:
print("-", end='')
print("-+")
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.
I'm trying to figure out how to select a specific character from a string. I know you can use the [0:0] and [0:-0] syntax etc... However I'm trying to do something different.
If a user enters "Hello, my name is [lol] bob [not[really]] john[son]"
or enters "[[[[]]][[][][]"
I'm trying to count how many square brackets have been typed and either left or right.
Thanks a lot guys for the instant response, a lot of help!
You can use str.count method if you only need to count them:
>>>s = "Hello, my name is [lol] bob [not[really]] john[son]"
>>>s.count('[') + s.count(']')
8
May be there have a better way, but it will do:
input = 'Hello, my name is [lol] bob [not[really]] john[son]'
print len(re.findall("\[|\]", input))
As the title suggests, I want to get a string, split it into individual bits to input into something like ord('') and get a value for each individual character in that string. Still learning python so things like this get super confusing :P. Furthermore, the process for encryption for each of the codes will just be to shift the alphabet's dec number by a specified value and decrypt into the shifted value, plus state that value for each character. How would i go about doing this? any and all help would be greatly appreciated!
message=input("Enter message here: ", )
shift=int(input("Enter Shift....explained shift: ", )
for c in list(message):
a=ord(c)
print c
This is the very basic idea of what i was doing (was more code but similar), but obviously it didn't work :C, the indented--> just means that it was indented, just don't know how to do that in stack overflow.
UPDATE: IT WORKS (kinda) using the loop and tweaking it according to the comments i got a list of every single ascii dec value for each character in the string!, ill try and use #Hugh Bothwell's suggestion within the loop and hopefully get some work done.
mystring = "this is a test"
shift = 3
encoded = ''.join(chr(ord(ch) + shift) for ch in mystring)
You'll have to do a little more if you want your alphabet to wrap around, ie encode('y') == 'b', but this should give you the gist of it.