I want to print a string with the same character repeated once right after it. For example, if the input is "hello", the program would output "hheelllloo". The code
for i in "hello":
print(i, end=i)
works, but I suppose I just do not understand it. I would expect this to give the same output as:
for i in "hello":
print(i + i)
Could anyone explain how the top code works?
The default value of end is a newline. So the second option is equivalent to:
for i in "hello":
print(i + i, end='\n')
You could do something like the second one with
for i in "hello":
print(i + i, end='')
since this explicitly sets end to the empty string so it won't print anything extra.
print(x) will append a newline character to the end of the string it prints.
One way to get rid of that is by setting end='' to have it append an empty string (equivalent to not appending anything at all) instead:
for i in "hello":
print(i + i, end='')
The other answers get to this point kind of circuitously, but the basic idea is that the default value for "end" is a newline, so each time you run through the loop it will print a newline and each successive iteration gets printed on a new line. By changing end to "end=i" or "i+i, end=''", you override this default and print each run of the loop on the same line.
Related
So I learnt the second course of python on edx and here is a code I wrote but don't really understand the part in the while loop. Could someone explain to me like I'm 6 years old what happens there?
Code:
# [ ] Print each word in the quote on a new line
quote = "they stumble who run fast"
start = 0
space_index = quote.find(" ")
while space_index != -1: #the code in while needs to be explained to me
print(quote[start:space_index])
start = space_index +1
space_index = quote.find(" ", space_index +1)
Your code attempts to demonstrate how to retrieve a sub-string from a string by index in Python, using a while loop having as stop condition that index.
The Python documentation on the function find() of string is here. Quoting from it:
The steps are these:
How to retrieve the index of the first occurrence of a given character in the string quote. In this line: quote.find(" "), it returns the index of the first position of a whitespace. So space_index will be equal to 4 when the while loop begins.
How to retrieve a sub-string from the string. In this line: quote[start:space_index] if you translate the variables start and space_index, what you have is: quote[0,4] which is equal to "they" in the first iteration.
How to increment the index. At the end of the while, you again do quote.find(" ", space_index +1) trying to get the index of a whitespace " ". But this time the position you start to search from is space_index+1 which on the first iteration will be 5. The function quote.find will return the value 12.
So in the 2nd iteration of the while: you'll be trying to get the sub-string quote[start:space_index] or substituting the values: quote[5:12] which will be the second word "stumble".
You should try to learn how to use a debugger of the IDE you are using, or try to print all intermediate values so you can see them.
The code basically prints each word separated by space line-by-line.
Commented Snippet:
# [ ] Print each word in the quote on a new line
quote = "they stumble who run fast"
start = 0 ## index of first character
space_index = quote.find(" ")
while space_index != -1: #the code in while needs to be explained to me
print(quote[start:space_index]) ## print characters from start index to space character
start = space_index +1 ## shift the start index to just after the up-coming space character
space_index = quote.find(" ", space_index +1) ## find the index of the next space character
This is for a homework assignment, we were asked to write a for loop that starts at the beginning of a user inputted string and then print every 2nd letter
I have tried to add a new line but that didn't solve the issue. I have tried to do it without using the range function by using
for char in s: and that produces the same results as using the range function
s = input('Please enter a string: ')
for i in range(len(s)):
print(i, s[0::2].upper())
If the word was Testing it should print out like this
T
S
I
G
with every letter capitalized. It wouldn't be double spaced I just had to format it look right on here. My code will pick up every 2nd letter but it prints it all out on one line instead of printing it out individually and then prints out TSIG 7 times.
This one is probably what you want.
INPUT:
s = raw_input('Please enter a string: ')
s=s[0::2].upper()
for i in range(len(s)):
print(s[i])
OUTPUT:
Please enter a string: TESTING
T
S
I
G
Try this:
s = 'testing'
for i in s[::2]:
print(i)
Your issue is that you are printing s[0::2].upper() every loop, and it is not affected by i:
def anti_vowel(text):
result = ""
for i in text:
while i not in "aeiouAEIOU":
result += i
return result
print anti_vowel("Hello")
This code removes vowels in a string
The ide just returns an empty string or keeps running without printing anything out.
The line:
while i not in "aeiouAEIOU":
will run forever if i is not a vowel, which happens in the case of Hello. Replace it with
if i not in "aeiouAEIOU":
while i not in "aeiouAEIOU":
result += i
Your loop condition only depends on the value of i, but your loop body doesn't change i. Therefore, if the loop is entered at all, it will loop forever.
You probably meant to write if i not in "aeiouAEIOU".
How can I take only one word from a line in file and save it in some string variable?
For example my file has line "this, line, is, super" and I want to save only first word ("this") in variable word. I tried to read it character by character until I got on "," but I when I check it I got an error "Argument of type 'int' is not iterable". How can I make this?
line = file.readline() # reading "this, line, is, super"
if "," in len(line): # checking, if it contains ','
for i in line:
if "," not in line[i]: # while character is not ',' -> this is where I get error
word += line[i] # add it to my string
You can do it like this, using split():
line = file.readline()
if "," in line:
split_line = line.split(",")
first_word = split_line[0]
print(first_word)
split() will create a list where each element is, in your case, a word. Commas will not be included.
At a glance, you are on the right track but there are a few things wrong that you can decipher if you always consider what data type is being stored where. For instance, your conditional 'if "," in len(line)' doesn't make sense, because it translates to 'if "," in 21'. Secondly, you iterate over each character in line, but your value for i is not what you think. You want the index of the character at that point in your for loop, to check if "," is there, but line[i] is not something like line[0], as you would imagine, it is actually line['t']. It is easy to assume that i is always an integer or index in your string, but what you want is a range of integer values, equal to the length of the line, to iterate through, and to find the associated character at each index. I have reformatted your code to work the way you intended, returning word = "this", with these clarifications in mind. I hope you find this instructional (there are shorter ways and built-in methods to do this, but understanding indices is crucial in programming). Assuming line is the string "this, line, is, super":
if "," in line: # checking that the string, not the number 21, has a comma
for i in range(0, len(line)): # for each character in the range 0 -> 21
if line[i] != ",": # e.g. if line[0] does not equal comma
word += line[i] # add character to your string
else:
break # break out of loop when encounter first comma, thus storing only first word
This is in python language.
I need to print this pattern, depending on the number of lines a user enters:
'##'
'# #'
The next pattern is three spaces away and so on...
This is my code but it prints the second number sign on a different line. I need them to go on the same line.
def drawPatternIII (lines):
for i in range(lines):
for j in range(1):
print('#')
for j in range(i+1):
print (' ', end = '')
print ('#')
please help!
You would need to add end="" to the first print() call. While you are at it, remove the pointless for loop with a single iteration.
A concise alternative would be
for i in range(lines):
print("#" + " "*i + "#")
The one liner version!
def drawPatternIII (lines):
list(map(print,["#" + " "*i + "#" for i in range(lines)]))