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
Related
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.
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'
I have simple script in python, want return per line the values
Tabs = # and \n
SCRIPT
output = ['192.168.0.1 #SRVNET\n192.168.0.254 #SRVDATA']
output = output[0].split('#')
output.split('\n')
OUTPUT
AttributeError: 'list' object has no attribute 'split'
After you split the first time, output is a list which doesn't support .split.
If splitting on two different items, you can use a regular expression with re.split:
>>> import re
>>> output = ['192.168.0.1 #SRVNET\n192.168.0.254 #SRVDADOS']
>>> re.split(r'\n|\s*#\s*',output[0]) # newline or comment (removing leading/trailing ws)
['192.168.0.1', 'SRVNET', '192.168.0.254', 'SRVDADOS']
You may want to group the IP with a comment as well, for example:
>>> [re.split(r'\s*#\s*',line) for line in output[0].splitlines()]
[['192.168.0.1', 'SRVNET'], ['192.168.0.254', 'SRVDADOS']]
The output of the line :
output = output[0].split('#')
is actually a list. ".split" always returns a list. In your case the output looks like this:
['192.168.0.1 ', 'SRVNET\n192.168.0.254 ', 'SRVDATA']
And as the error rightly points out, a list cannot be "split" using the ".split" which it does not support.
So now if you wanna further split the list when "#" is encountered, then this can be solved by iterating through the list and calling the split function like this:
output=['192.168.0.1 ', 'SRVNET\n192.168.0.254 ', 'SRVDATA']
for i in output:
if "\n" in i:
print("yes")
output_1=i.split("\n")
This will give the "output_1" as:
['SRVNET', '192.168.0.254 ']
If you don't want to use re, then you need to apply split("\n") to each element of output[0].split("#"), then concatenate the results together again. One way to do that is
result = [y for x in output[0].split("#") for y in x.split("\n")]
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...
>>> print(("hello\nworld", "hello2"))
('hello\nworld', 'hello2')
How to make it print:
('hello
world', 'hello2')
I mean it must not print \n as the symbol but implement this symbol and make a new line.
Python version is 3.4.
I tried to use pprint but it does the same:
>>> import pprint
>>> pp = pprint.PrettyPrinter(indent=4)
>>> pp.pprint(("hello\nworld"))
'hello\nworld'
There isn't anything that will do that kind of printing for you automatically. Python containers by default use repr to convert their contents to strings (even when you call str on the container, rather than repr). This is to avoid ambiguity from things like ["foo, bar", "baz"] (if the quotes didn't get included, you couldn't tell if there were two or three items were in the list).
You can do your own formatting of your tuple, however, and get the output you want:
print("({})".format(", ".join(tup)))
If you didn't want the parentheses and commas, it would be a simple matter of using the * operator:
>>> t = ("hello\nworld", "hello2")
>>> print(*t)
hello
world hello2
If you want it to print the parentheses and commas but also turn '\n' into newlines, you'll have to code that behavior, as #Peter says.
>>> print('(' + ', '.join(t) + ')')
(hello
world, hello2)
Writing:
print("('Hello\nworld', 'hello2')")
will literally print:
('hello
world', 'hello2')
If you are just wanting a new line inserted in your string, use this:
print("Line1\nLine2")
the \n is the escape sequence for a new line, terminating the current line and signaling the start of the next line.
For comparing it to the code you have, you should note the placement of the " symbols, denoting the beginning and end of the string.
>>> t = ("hello\nworld", "hello2")
>>> print '({})'.format(', '.join("'{}'".format(value) for value in t))
('hello
world', 'hello2')
This won't be correct if the strings contain ' marks.
Be aware that Python's formatting does clever things to deal with strings containing quotation marks.
Here is a more complex example from some Ansible output that was annoying me:
import pprint
f={
"failed": True,
"msg": "the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'dict object' has no attribute 'uid'\n\nThe error appears to have been in '/usr/local/etc/ansible/roles/singleplatform-eng.users/tasks/main.yml': line 7, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: Per-user group creation\n ^ here\n"
}
def ppdump(data):
print pprint.pformat(data, indent=4, width=-1).replace('\\n', '\n')
ppdump(f)
{ 'failed': True,
'msg': "the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'dict object'
has no attribute 'uid'
The error appears to have been in '/usr/local/etc/ansible/roles/singleplatform-eng.users/tasks/main.yml': line 7, column 3, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
- name: Per-user group creation
^ here
"}
The problem is that pprint escapes out newlines, so I just unescape them.
You can do something like this:
v = [(1,2),(2,3),(4,5)]
for item in v:
n1,n2 = item
print(n1,n2)
Refer to this https://i.stack.imgur.com/rEfiM.png