printing a python code multiple times (NO LOOPS0 - python

I've been having trouble getting a specific print in Python 3.4
Input:
str=input("Input Here!!!:")
num = len(str)
x = num
print (((str))*x)
but I'm looking for an output that prints str x times, without using a loop.
for example if I enter:
Input Here!!!: Hello
I would get:
>>>Hello
>>>Hello
>>>Hello
>>>Hello
>>>Hello

You need to add a newline if you want the output on different lines:
In [10]: n = 5
In [11]: s = "hello"
In [12]: print((s+"\n")* n)
hello
hello
hello
hello
hello
It is not possible to get the output as if each string were the output of a new command. The closest to your expected output will be the code above.

You should never use built-in keywords, types for variable names. str is a built in type like list, int etc. Next time you would try to use it, will give you errors.
Ex -
>>> str = 'apple'
Now let's try to build a simple list of no.s as string.
>>> [ str(i) for i in range(4)]
Traceback (most recent call last):
File "<pyshell#298>", line 1, in <module>
[ str(i) for i in range(4)]
TypeError: 'str' object is not callable
Since we have already replaced our str with a string. It can't be called.
So let's use 's' instead of 'str'
s=input("Input Here!!!:")
print ( s * len(s) )
If you want output in different lines
print ( (s+"\n")* len(s) )

I don't know what exactly do you want to achieve. We can always replicate looping with a recursive function.
def input(s):
print(s)
def pseudo_for(n, my_func, *args):
if n==0:
return
else:
'''
Write function or expression to be repeated
'''
my_func(*args)
pseudo_for(n-1, my_func, *args)
pseudo_for(5, input, "Hello")

You can use join with a list comprehension:
>>> s='string'
>>> print('\n'.join([s for i in range(5)]))
string
string
string
string
string
Technically a list comprehension is a 'loop' I suppose, but you have not made clear what you mean by 'without using a loop'
You can also use string formatting in Python:
>>> fmt='{0}\n'*5
>>> fmt
'{0}\n{0}\n{0}\n{0}\n{0}\n'
>>> print(fmt.format('hello'))
hello
hello
hello
hello
hello
But that will have an extra \n at the end (as will anything using *n)
As Tim points out in comments:
>>> print('\n'.join([s]*5))
string
string
string
string
string
Is probably the best of all...

Related

Replace a number with a word

Given a string. Replace in this string all the numbers 1 by the word one.
Example input:
1+1=2
wished output:
one+one=2
I tried the following but does not work with an int:
s=input()
print(s.replace(1,"one"))
How can I replace an integer?
You got a TypeError like below.
Use '1' of type str as first argument (string instead number) because you want to work with strings and replace parts of the string s.
Try in Python console like:
>>> s = '1+1=2'
>>> print(s.replace(1,"one"))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: replace() argument 1 must be str, not int
>>> print(s.replace('1',"one"))
one+one=2
or simply use the string-conversion method str():
s.replace(str(1), 'one')
Whilst you could simply use a replace(), I would suggest instead using a python dictionary. Defining each number to a word, that would then switch. Like this.
conversion = {
1: 'one',
2: 'two'
}
You can then use this like a dictionary
print(conversion[1]) # "one"
print(conversion[2]) # "two"
This simply makes your code more adaptable, in case you want to convert some numbers and not all. Just an alternative option to consider.

What is point of using the concatenation(+) in Python when commas(,) do the job?

print("This is a string" + 123)
Concatenating throws error, but using a comma instead does the job.
As you already been told, your code raises an error because you can only concatenate two strings. In your case one of the arguments of the concatenation is an integer.
print("This is a string" + str (123))
But your question is more something "plus vs. comma". Why one should ever use + when , works?
Well, that is true for print arguments, but actually there are other scenario in which you may need a concatenation. For example in an assignment
A = "This is a string" + str (123)
Using comma, in this case, would lead to a different (and probably unexpected) result. It would generate a tuple and not a concatenation.
Hey here you are trying to concatenate the string and integer. It will throw type error.
You can try something like
print("This is a string"+str(123))
Commas (,) are not actually concatenating the values it's just printing it in a fashion that it looks like concatenation.
Concatenation on the Other hand will actually join two strings.
That's one case of print(). However if you do need a string, concatenation is the way:
x = "This is a string, "+str(123)
gets you " This is a string, 123"
Should you write
x = "This is a string", 123
you would get the tuple ("This is a string",123). That's not a string but an entirely different type.
If you have your int value in a variable, you can print it out with f-string (format string).
Format take more inputs like print(("one text number {num1} and another text number {num2}").format(num1=variable1, num2=variable2)
x = 123
print(("This is a string {x}").format(x=x))
The above code outputs:
This is a string 123
You can read more about it here:
python-f-strings
# You can concatenate strings and int variables with a comma, however a comma will silently insert a space between the values, whereas '+' will not. Also '+' when used with mixed types will give unexpected results or just error altogether.
>>> start = "Jaime Resendiz is"
>>> middle = 21
>>> end = "years old!
>>> print(start, middle, end)
>>> 'Jaime Resendiz is 21 years old!'
It's simple cause 123 is an int type and you cannot concatenate int with str type.
>>> s = 123
>>> type(s)
<class 'int'>
>>>
>>> w = "Hello"+ s
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
>>>
>>>
>>> w = "Hello" + str(s)
>>>
>>> w
'Hello123'
>>>
You can see the error , so you can convert the s variable that its value is 123 to string using str() function. But situations like this that you want to concatenate strings with other types? I think you should use f-strings
Example
>>> boolean = True
>>> fl = 1.2
>>> integer = 100
>>>
>>> sentence = f"Hello variables! {boolean} {fl} {integer}"
>>> sentence
'Hello variables! True 1.2 100'

printing multiple lists in python

Hey I wrote a python code (python 2.7.3) with multiple lists, but when I try to print them they always come with a space. I want to print the list in continuous manner but I'm unable to do so. I have one list which have integer values and other with character.
Eg: list1 (integer list has 123) and list2(character list has ABC).
Desired Output: ABC123
What I'm getting: ABC 123
What I did:
print "".join(list2),int("".join(str(x) for x in list1))
Any suggestion what I'm doing wrong?
l = ["A","B","C"]
l2 = [1,2,3]
print "".join(l+map(str,l2))
ABC123
map casts all ints to str, it is the same as doing [str(x) for x in l2].
The space comes from the print statement. It automatically inserts a space between items separated with comma. I suppose you don't need to covert the concatenated string into an integer, then you concatenate strings from join and print them as one.
print "".join(list2)+"".join(str(x) for x in list1)
Alternatively you can switch to python3's print function, and use its sep variable.
from __future__ import print_function
letters=['A','B','C']
nums=[1,2,3]
print("".join(letters),int("".join(str(x) for x in nums)), sep="")
Try concatenating the two lists you want while printing. Use "+" instead of ",".
Here 'int' will give error as you can concatenate only strings. So try,
print "".join(list2)"".join(str(x) for x in list1)
The , is what's adding the space since you are printing two things, a string 'ABC' and an integer 123. Try using +, which directly adds two strings together so you can print the string 'ABC123'
>>> list1=[1,2,3]
>>> list2=['A','B','C']
>>> print "".join(list2),int("".join(str(x) for x in list1))
ABC 123
>>> print "".join(list2)+"".join(str(x) for x in list1)
ABC123
print adds a single space automatically between commas.
You can use the new print function:
from __future__ import print_function
print("".join(list2),int("".join(str(x) for x in list1)), sep="")
See docs.
Note: This function is not normally available as a built-in since the
name print is recognized as the print statement. To disable the
statement and use the print() function, use this future statement at
the top of your module

What does [1] mean in this code?

I have just started to learn python. I got this statement:
output= " name: abc"
log =output.split("=")[1]
What does the [1] denote? Why is it used?
The [1] is indexing into the list returned by output.split("="); if that method returns a list of 2 or more elements, the [1] indexes the second element.
In your specific case, it'll raise an IndexError, as there is no = in output. Because of this, the output.split("=") method returns just a list with just one string.
You can try things like these in a Python interpreter prompt:
>>> output= " name: abc"
>>> output.split('=')
[' name: abc']
>>> output.split('=')[0]
' name: abc'
>>> output.split('=')[1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
Had you split on : instead you'd have gotten a more useful result:
>>> output.split(':')[1]
' abc'
This is what the statement means:
output= " name: abc"
log =output.split("=")[1]
Take the string output and split it on '=' and then get the second element in the resulting list (index 1)
However, you can see that your output doesn't really contain any =, you probably want:
output= "name=abc"
Here is the breakdown:
a = output.split('=')
>>> a
['name', 'abc']
>>> a[1]
abc
this is useful when you know for sure the string has the (=) equal-to symbol or the any character that you are splitting with. so that it splits the string and returns the list.
and then from the list you can choose which part of string is useful for you
in your case it will return IndexError since it is not returning a list.
output= " name= abc"
log =output.split("=")[1]
in this case this will be useful

Indexing by word in a list

I feel like this is a really simple question,
but I need help figuring out.
So, I have the following:
str = 'hello world'
str.split() # ['hello','world']
I want to index 'world' but str[1] returns 'e', which is the second character in the list.
How do I index by word instead of character?
Please help me out and thank you in advance.
(Please don't tell me to do str[5:]... I wanna know how to index words in general)
You need to index the result of my_str.split():
my_str = "hello world"
words = my_str.split()
print words[1]
(Renamed the variable to my_str to avoid shadowing the built-in.)
Note that my_str.split() does not change my_str in any way. String objects are immutable in Python and can't be changed. Instead, my_str.split() returns a list of strings that can be indexed.
str is your string, not the result of str.split(). You need to assign the result to something (preferably something not called str, since that's the name of the builtin str type and also a rather bad name to use for a list, even one returned from str.split().
>>> s = 'hello world'
>>> l = s.split()
>>> l[1]
'world'
You're indexing str, which is a string (you didn't reassign value to str after splitting so it went down the drain).
Use
str.split()[1]
or even better save the split result, and index that:
spl = str.split()
spl[1]
The split returns a list, instead of splitting in place:
str = 'hello world'
str_words = str.split() # split returns a list
print str_words[0] # prints first word "hello"

Categories

Resources