I ask the user to enter it's name and I print the pattern
eg:
W
WO
WOR
WORL
WORLD
s=input("Enter your name")
l=s.split()
i=len(l)
for m in range(0,i):
for s in range(0,m):
print(s)
print()
I have written this program where am I wrong please help. A beginner here
Others have given you code that does what you want it to do; I'll try to explain why your code doesn't do what you think it would do.
#s=input("Enter your name")
# Let's pretend that the given word from the user was 'WORLD' as in your example.
s = "WORLD"
l=s.split()
The above line s.split() uses the default-behaviour of the built-in str.split() method. Which does the following if we look at the help-file:
split(self, /, sep=None, maxsplit=-1)
Return a list of the words in the string, using sep as the delimiter string.
sep
The delimiter according which to split the string.
None (the default value) means split according to any whitespace,
and discard empty strings from the result.
That means that it will try to split your given string on each whitespace-character inside of it and return a list containing the results. "WORLD".split() would therefore return: ['WORLD']
i=len(l)
This returns 1, because the result of s.split().
Now let's break down what happens inside of the for-loop.
# This is essentially: for m in range(0, 1) which will only loop once, because range is non-inclusive
for m in range(0,i):
# This is range-command will not execute, because the first value of m will be 0
# Because range is non-inclusive, running range(0, 0) will not return a value.
# That means that nothing inside of the for-loop will execute.
for s in range(0,m):
print(s)
print()
All of this results in only the print() statement inside of the first for-loop being executed, and it will only be executed once because of how the range-function works with the values it has been given.
We can do this without using 2 loops.
s = input("Enter your name")
for i in range(len(s)+1):
print(s[:i])
#Output:
W
WO
WOR
WORL
WORLD
Don't complicate the code unnecessarily.
A string you can think of as a list of characters on which to iterate, without resorting to splitting.
If you use Python's List Slicing, you can point to the positions of the characters you are interested in printing.
Your code becomes:
name = input("Enter your name: ")
for i in range(len(name)):
print(name[:i+1])
Related
Please write a program which asks the user to type in a string. The program then prints out all the substrings which begin with the first character, from the shortest to the longest. Have a look at the example below.
Please type in a string: test
t
te
tes
test
Obviously my code is not the way it supposed to be:
stg = input("Please type in a string: ")
print(stg[0])
print(stg[0:5])
print(stg[0:10])
print(stg[10:50])
print(stg[:])
ok, this is a homework and I don't give you the exact solution... but as some points:
you have a string and want to print first 1 letter, first 2 letters and so on... so your range end must increase one by one...
you don't know about input length so you can't use hard code and use a loop
for loop you need to know about string length and use a builtin method for getting the length...
any question? ask it...
userString = input("Gimme String: ")
# Looping based on the given String
# Last Value is not included so you need to increment the value by one
for i in range(len(userString)):
# Last Value is not included so you need to increment the value by one
print(userString[:i+1])
#Alternative
for i in range(1,len(userString)+1):
print(userString[:i])
stg = input("Please type in a string: ")
print("\n".join([stg[0:i+1] for i in range (len(stg))]))
Output:
t
te
tes
test
Just use simple for loop
stg = 'test'
temp_str = ''
for i in range(len(stg)):
temp_str = temp_str + stg[i]
print(temp_str)
I've just started learning to code Python today on Grok Learning and I'm currently stuck on this problem. I have to create a code that reads a message and:
read the words in reverse order
only take the words in the message that start with an uppercase letter
make everything lowercase
I've done everything right but I can't get rid of a space at the end. I was wondering if anyone knew how to remove it. Here is my code:
code = []
translation = []
msg = input("code: ")
code = msg.split()
code.reverse()
for c in code:
if c[0].isupper():
translation.append(c)
print("says: ", end='')
for c in translation:
c = c.lower()
print(c, end = ' ')
Thank you :)
You need to iterate for all of the letters in translation but the last and print it separately without the space:
for c in translation[:-1]:
c = c.lower()
print(c, end = ' ')
print(translation[-1], end='')
You can simply use join() and f-strings.
result = ' '.join(translation).lower()
print(f"says: {result}")
This is a common problem:
You have a sequence of n elements
You want to format them in a string using a separator between the elements, resulting in n-1 separators
I'd say the pythonic way to do this, if you really want to build the resulting string, is str.join(). It takes any iterable, for example a list, of strings, and joins all the elements together using the string it was called on as a separator. Take this example:
my_list = ["1", "2", "3"]
joined = ", ".join(my_list)
# joined == "1, 2, 3"
In your case, you could do
msg = "Hello hello test Test asd adsa Das"
code = msg.split()
code.reverse()
translation = [c.lower() for c in code if c[0].isupper()]
print("says: ", end='')
print(" ".join(translation))
# output:
# says: das test hello
For printing, note that print can also take multiple elements and print them using a separator. So, you could use this:
print(*translation, sep=" ")
You could also leave out explicitly setting sep because a space is the default:
print(*translation)
I am trying to abbreviate a first name and a last name. For example, if I enter Diesan Romero (that's my name), I need to return the initials D.R with that intermediate point.
I had no idea where to start. So I went to the Python documentation and tried to convert the text string to a list, iterate the list, and then choose those characters that were uppercase. This is the code that I have achieved so far.
def convertToList(name):
lista = []
for i in name:
if i.isupper():
lista.append(i)
return lista
if __name__ == "__main__":
print(convertToList("Diesan Romero"))
In that code I try to create the list, but it only returns me one value.
def convertToList(name):
final_name = []
name_list = name.split()
for i in name_list:
final_name.append(i[0])
print '.'.join(final_name)
convertToList('Diesan Romero')
If your names will always be in the format - “first last”, you may be able to do the following:
def get_initials(name):
names = name.split(' ')
return ' '.join([f"{n[0]}." for n in names])
print(get_initials('John Doe'))
Looks like you are returning lista as soon as you first find an upper-case letter. Try de-indenting the "return" by two tabs to shift it after the end of the for loop.
I have a question that ask the user to input a string THE and split it as three different string, output like this T,H,E I tried but output same with input.
def func():
str1=input("Enter String : ")
','.split(str1)
print(str1)
func()
Output
THE
And second question is that ask the user to enter a string T H E S T R I N G and the output should THE STRING when one space occurs remove it and if more then one then replace it whit single space.
Here is my code.
def func2():
str2=input("Enter String :")
for i in str2:
if(i.isspace==True):
del(i)
else:
str2=str2+i
print(str2)
func2()
output is.
T H E S T R I N GTHESTRING
I have no idea how to correct it.
You cannot store the value after splitting and not printing it.
Just change ','.split(str1) with str1 =str1.split(',') and print str1.
Read the documentation for the split method: it doesn't apply to your first problem at all. Instead, the solution is much simpler: take the individual characters and join them with commas:
char_list = list(str1)
str2 = ','.join(char_list)
... and print or return str3. Yes, this can be shortened; I'm teaching you the individual steps.
As the posting guidelines tell you, each question must have a separate posting. I'll leave the other answer for your other posting.
There's a distinction between in-place and standard operators. In-place functions actually change in the input, while standard operators give a result as output, and that output then has to be assigned or passed to something else for it to be used. (Also, you don't have the syntax correct; it should be 'str1.split(',')) The split operator is a standard operator; 'str1.split(',') doesn't affect the value of str1, but instead creates a new result. Since you're not doing anything with that result, it gets thrown away. You could do split_string ='str1.split(',') and then print(new_string) or just print('str1.split(',').
Also, the problem statements "split it as three different string" and "output like this T,H,E" are contradictory. If you want a list of three strings, that would be ['T','H','E']. Saying you want an output of T,H,E makes it sound like you want a single string with commas between the letters.
I have a string 'A1T1730'
From this I need to extract the second letter and the last four letters. For example, from 'A1T1730' I need to extract '1' and '1730'. I'm not sure how to do this in Python.
I have the following right now which extracts every character from the string separately so can someone please help me update it as per the above need.
list = ['A1T1730']
for letter in list[0]:
print letter
Which gives me the result of A, 1, T, 1, 7, 3, 0
my_string = "A1T1730"
my_string = my_string[1] + my_string[-4:]
print my_string
Output
11730
If you want to extract them to different variables, you can just do
first, last = my_string[1], my_string[-4:]
print first, last
Output
1 1730
Using filter with str.isdigit (as unbound method form):
>>> filter(str.isdigit, 'A1T1730')
'11730'
>>> ''.join(filter(str.isdigit, 'A1T1730')) # In Python 3.x
'11730'
If you want to get numbers separated, use regular expression (See re.findall):
>>> import re
>>> re.findall(r'\d+', 'A1T1730')
['1', '1730']
Use thefourtheye's solution if the positions of digits are fixed.
BTW, don't use list as a variable name. It shadows builtin list function.
Well you could do like this
_2nd = lsit[0][1]
# last 4 characters
numbers = list[0][-4:]
You can use the function isdigit(). If that character is a digit it returns true and otherwise returns false:
list = ['A1T1730']
for letter in list[0]:
if letter.isdigit() == True:
print letter, #The coma is used for print in the same line
I hope this useful.