>>> 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
Related
When i assign a windows path as a value in dictionary, the backward slash gets added.
I did try using raw string.
p = "c:\windows\pat.exe"
print p
c:\windows\pat.exe
d = {"p": p}
print d
{'p': 'c:\\windows\\pat.exe'}
Tried it as raw string
d = {"p": r"%s" % p}
print d
{'p': 'c:\\windows\\pat.exe'}
I dont want the backslash to added when assigned to value in dictionary.
This is a mistake that's very common among people new to Python.
TL;DR:
>>> print "c:\windows\pat.exe" == 'c:\\windows\\pat.exe'
True
Explanation:
In the first instance, where you're assigning a value to the string p and then printing p, Python gets the string to print itself and it does so by outputting its literal value. In your example:
>>> p = "c:\windows\pat.exe"
>>> print p
c:\windows\pat.exe
In Python 3, the same:
>>> p = "c:\windows\pat.exe"
>>> print(p)
c:\windows\pat.exe
In the second instance, since you're creating and then printing a dictionary, Python asks the dictionary to print itself. It does so by printing a short Python code representation of itself, since there is no standard simple way of printing a dictionary, like there is for variables with simple types like strings or numbers.
In your example (slightly modified to work by itself):
>>> d = {"p": "c:\windows\pat.exe"}
>>> print d
{'p': 'c:\\windows\\pat.exe'}
So, why does the value of p in the Python code representation have the double backslashes? Because a single backslash in a string literal has an ambiguous meaning. In your example, it just so happens that \w and \p don't have special meanings in Python. However, you've maybe seen things like \n and perhaps \t used in strings to represent a new line or a tab character.
For example:
>>> print "Hello\nworld!"
Hello
world!
So how does Python know when to print a new line and when to print \n literally, when you want to? It doesn't. It just assumes that if the character after the \ doesn't make for a special character, you probably wanted to write a \ and if it is, you wanted to write the special character. If you want to literally write a \, regardless of what follows, you need to follow up the escape character (that's what the \ is called in this context) with another one.
For example:
>>> print "I can see \\n"
I can see \n
That way, there is no ambiguity and Python knows exactly what is intended. You should always write backslashes as double backslashes in normal string literals, instead of relying on luck in avoiding control characters like \n or \t. And that's why Python, when printing its code version of your string "c:\windows\pat.exe", prefers to write it as 'c:\\windows\\pat.exe'. Using single quotes, which are preferred even though double quotes are fine too and using double backslashes.
It's just how it is written in code, "really" your string has single backslashes and the quotes are of course not part of it at all.
If you don't like having to write double backslashes, you can consider using 'raw strings', which is prefixing a string with r or R, telling Python to ignore special characters and take the string exactly as written in code:
>>> print r"This won't have \n a line break"
This won't have \n a line break
But watch out! This doesn't work if you want your last characters in the string to be an odd number of \, for reasons not worth getting into. In that case, you have no other recourse than writing the string with double backslashes:
>>> print r"Too bad\"
File "<stdin>", line 1
print r"Too bad\"
^
SyntaxError: EOL while scanning string literal
>>> print r"Too bad\\"
Too bad\\
>>> print "Too bad\\"
Too bad\
Maybe it is not a problem, because when you print the values (not the whole dictionary) the string will have one backslash
p = "c:\windows\pat.exe"
d = {"p": p}
print (d)
{'p': 'c:\\windows\\pat.exe'}
for i in d:
print("key:", i, " value:", d[i])
Output
{'p': 'c:\\windows\\pat.exe'}
key: p value: c:\windows\pat.exe
>>>
This question already has answers here:
Python strip unexpected behavior
(2 answers)
Closed 4 years ago.
value = div.xpath('normalize-space(.)').extract()[0].strip('{}:'.format(key)).strip()
The code above sometimes strips the last character from the word. After removing the code after extract() all the data came back fine but in a list.
Example :
Unknown from Duration: Unknown turns into unknow
Movie from Type: Movie turns into Movi
Why does this happen?
I tried this in Python shell and it also strips the last characters
>>> value = ['Type: Movie']
>>> value[0].strip('{}:'.format('Type')).strip()
'Movi'
I expect it to return Movie instead of e getting stripped.
It seems that this .strip('{}:'.format('Type')) is responsible. I removed the last strip() it only return data with spaces.
Edit: It seems that strip() takes characters in inputted string and remove them instead of removing exact strings. That is why the data came out broken. I think a string split then slice is good.
Edit 2:
Seems like answers by Austin and Pankaj Singhal is good and bug free for my use case.
Use a split on 'Type: ' and take the second item:
value = ['Type: Movie']
print(value[0].split('Type: ')[1])
# Movie
Talking about your code, strip is not meant for what you are trying to do. strip only removes characters from at the ends.
You could use lstrip (which returns a copy of the string with only leading characters removed), instead of strip (which returns a copy of the string with leading and trailing characters removed):
>>> 'Type: Movie'.lstrip("Type:").strip()
'Movie'
>>> 'Type: Something with Type'.lstrip("Type:").strip()
'Something with Type'
>>> 'Type: Something with Type:'.lstrip("Type:").strip()
'Something with Type:'
>>>
OR:
>>> value = ['Type: Movie']
>>> value[0][value[0].find(':')+2:]
'Movie'
>>>
And of course, this is another option similar to the first one, just using lstrip:
>>> value[0][value[0].find(':')+1:].lstrip()
'Movie'
>>>
OR:
>>> value[0].lstrip(value[0][:value[0].find(':')+2])
'Movie'
Note: here find can be replaced with index
str.strip does not strip that exact string, but each character in that string, i.e. strip("Type:") will remove each T, y, p, etc. from the beginning and end of the string.
Instead, you could use a regular expression with the ^ anchor to only match substrings at the beginning of the string.
>>> value = ['Type: Movie with Type: in its name']
>>> key = "Type"
>>> re.sub(r"^{}: ".format(key), "", value[0])
'Movie with Type: in its name'
I have a string opening with { and closing with }. This brackets are always at first and at last and must appear, they can not appear in the middle. as following:
{-4,10746,.....,205}
{-3,105756}
what is the most efficient way to remove the brackets to receive:
-4,10746,.....,205
-3,105756
s[1:-1] # skip the first and last character
You can also use replace method.
In [1]: a = 'hello world'
In [3]: a.replace('l','')
Out[3]: 'heo word'
Since you were not clear there are two possibilities it may be a string or a set
If it is a set this might work:
a= {-4, 205, 10746}
",".join([str(s) for s in a])
output='10746,-4,205'
If it is a string this will work:
a= '{-4, 205, 10746}'
a.replace("{","").replace("}","")
output= '-4, 205, 10746'
Since there is no order in set the output is that way
Here's a rather roundabout way of doing exactly what you need:
l = {-3,105756}
new_l = []
for ch in l:
if ch!='{' and ch!= '}':
new_l.append(ch)
for i,val in enumerate(new_l):
length = len(new_l)
if(i==length-1):
print str(val)
else:
print str(val)+',',
I'm sure there are numerous single line codes to give you what you want, but this is kind of what goes on in the background, and will also remove the braces irrespective of their positions in the input string.
Just a side note, answer by #dlask is good to solve your issue.
But if what you really want is to convert that string (that looks like a set) to a set object (or some other data structure) , you can also use ast.literal_eval() function -
>>> import ast
>>> s = '{-3,105756}'
>>> sset = ast.literal_eval(s)
>>> sset
{105756, -3}
>>> type(sset)
<class 'set'>
From documentation -
ast.literal_eval(node_or_string)
Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.
The safest way would be to strip:
'{-4, 205, 10746}'.strip("{}")
Have a set of string as follows
text:u'MUC-EC-099_SC-Memory-01_TC-25'
text:u'MUC-EC-099_SC-Memory-01_TC-26'
text:u'MUC-EC-099_SC-Memory-01_TC-27'
These data i have extracted from a Xls file and converted to string,
now i have to Extract data which is inside single quotes and put them in a list.
expecting output like
[MUC-EC-099_SC-Memory-01_TC-25, MUC-EC-099_SC-Memory-01_TC-26,MUC-EC-099_SC-Memory-01_TC-27]
Thanks in advance.
Use re.findall:
>>> import re
>>> strs = """text:u'MUC-EC-099_SC-Memory-01_TC-25'
text:u'MUC-EC-099_SC-Memory-01_TC-26'
text:u'MUC-EC-099_SC-Memory-01_TC-27'"""
>>> re.findall(r"'(.*?)'", strs, re.DOTALL)
['MUC-EC-099_SC-Memory-01_TC-25',
'MUC-EC-099_SC-Memory-01_TC-26',
'MUC-EC-099_SC-Memory-01_TC-27'
]
You can use the following expression:
(?<=')[^']+(?=')
This matches zero or more characters that are not ' which are enclosed between ' and '.
Python Code:
quoted = re.compile("(?<=')[^']+(?=')")
for value in quoted.findall(str(row[1])):
i.append(value)
print i
That text: prefix seems a little familiar. Are you using xlrd to extract it? In that case, the reason you have the prefix is because you're getting the wrapped Cell object, not the value in the cell. For example, I think you're doing something like
>>> sheet.cell(2,2)
number:4.0
>>> sheet.cell(3,3)
text:u'C'
To get the unwrapped object, use .value:
>>> sheet.cell(3,3).value
u'C'
(Remember that the u here is simply telling you the string is unicode; it's not a problem.)
In C++, \n is used, but what do I use in Python?
I don't want to have to use:
print (" ").
This doesn't seem very elegant.
Any help will be greatly appreciated!
Here's a short answer
x=' '
This will print one white space
print(x)
This will print 10 white spaces
print(10*x)
Print 10 whites spaces between Hello and World
print(f"Hello{x*10}World")
If you need to separate certain elements with spaces you could do something like
print "hello", "there"
Notice the comma between "hello" and "there".
If you want to print a new line (i.e. \n) you could just use print without any arguments.
A lone print will output a newline.
print
In 3.x print is a function, therefore:
print()
print("hello" + ' '*50 + "world")
Any of the following will work:
print 'Hello\nWorld'
print 'Hello'
print 'World'
Additionally, if you want to print a blank line (not make a new line), print or print() will work.
First and foremost, for newlines, the simplest thing to do is have separate print statements, like this:
print("Hello")
print("World.")
#the parentheses allow it to work in Python 2, or 3.
To have a line break, and still only one print statement, simply use the "\n" within, as follows:
print("Hello\nWorld.")
Below, I explain spaces, instead of line breaks...
I see allot of people here using the + notation, which personally, I find ugly.
Example of what I find ugly:
x=' ';
print("Hello"+10*x+"world");
The example above is currently, as I type this the top up-voted answer. The programmer is obviously coming into Python from PHP as the ";" syntax at the end of every line, well simple isn't needed. The only reason it doesn't through an error in Python is because semicolons CAN be used in Python, really should only be used when you are trying to place two lines on one, for aesthetic reasons. You shouldn't place these at the end of every line in Python, as it only increases file-size.
Personally, I prefer to use %s notation. In Python 2.7, which I prefer, you don't need the parentheses, "(" and ")". However, you should include them anyways, so your script won't through errors, in Python 3.x, and will run in either.
Let's say you wanted your space to be 8 spaces,
So what I would do would be the following in Python > 3.x
print("Hello", "World.", sep=' '*8, end="\n")
# you don't need to specify end, if you don't want to, but I wanted you to know it was also an option
#if you wanted to have an 8 space prefix, and did not wish to use tabs for some reason, you could do the following.
print("%sHello World." % (' '*8))
The above method will work in Python 2.x as well, but you cannot add the "sep" and "end" arguments, those have to be done manually in Python < 3.
Therefore, to have an 8 space prefix, with a 4 space separator, the syntax which would work in Python 2, or 3 would be:
print("%sHello%sWorld." % (' '*8, ' '*4))
I hope this helps.
P.S. You also could do the following.
>>> prefix=' '*8
>>> sep=' '*2
>>> print("%sHello%sWorld." % (prefix, sep))
Hello World.
rjust() and ljust()
test_string = "HelloWorld"
test_string.rjust(20)
' HelloWorld'
test_string.ljust(20)
'HelloWorld '
Space char is hexadecimal 0x20, decimal 32 and octal \040.
>>> SPACE = 0x20
>>> a = chr(SPACE)
>>> type(a)
<class 'str'>
>>> print(f"'{a}'")
' '
Tryprint
Example:
print "Hello World!"
print
print "Hi!"
Hope this works!:)
this is how to print whitespaces in python.
import string
string.whitespace
'\t\n\x0b\x0c\r '
i.e .
print "hello world"
print "Hello%sworld"%' '
print "hello", "world"
print "Hello "+"world
Sometimes, pprint() in pprint module works wonder, especially for dict variables.
simply assign a variable to () or " ", then when needed type
print(x, x, x, Hello World, x)
or something like that.
Hope this is a little less complicated:)
To print any amount of lines between printed text use:
print("Hello" + '\n' *insert number of whitespace lines+ "World!")
'\n' can be used to make whitespace, multiplied, it will make multiple whitespace lines.
In Python2 there's this.
def Space(j):
i = 0
while i<=j:
print " ",
i+=1
And to use it, the syntax would be:
Space(4);print("Hello world")
I haven't converted it to Python3 yet.
A lot of users gave you answers, but you haven't marked any as an answer.
You add an empty line with print().
You can force a new line inside your string with '\n' like in print('This is one line\nAnd this is another'), therefore you can print 10 empty lines with print('\n'*10)
You can add 50 spaces inside a sting by replicating a one-space string 50 times, you can do that with multiplication 'Before' + ' '*50 + 'after 50 spaces!'
You can pad strings to the left or right, with spaces or a specific character, for that you can use .ljust() or .rjust() for example, you can have 'Hi' and 'Carmen' on new lines, padded with spaces to the left and justified to the right with 'Hi'.rjust(10) + '\n' + 'Carmen'.rjust(10)
I believe these should answer your question.