\n and \t method won't combine with variable? - python

Can't we use \t and \n in variables?
var1 = " Ryan "
print (\tvar1.strip() + \nvar1.lstrip() + \nvar1.rstrip())
I get an error:
syntax error : unexpected character after line continuation character

You need to treat them as regular characters and concatenate them properly with other strings:
print('\t' + var1.strip() + '\n' + var1.lstrip() + '\n' + var1.rstrip())
(edit from ShadowRanger's comments):
If you are on Python 3.6+, you can use f-strings instead of the + operator:
print(f"\t{var1.strip()}\n{var1.lstrip()}\n{var1.rstrip()}")
If you can't use f-strings yet, you can use the regular str.format method:
print("\t{}\n{}\n{}".format(var1.strip(), var1.lstrip(), var1.rstrip()))
You can also include them directly in literal strings:
str1 = "\tabc\ndef"

Related

Error in python string

when I type this code in python it shows this error
>>> 'Ahmed' + \t 'Ashraf '
SyntaxError: unexpected character after line continuation character
what does this error mean ??
The \t escape sequence has to be inside a string literal, so the correct syntax is:
'Ahmed' + '\t' + 'Ashraf '
Outside a string literal, \ is used to indicate that you're continuing a statement on the next line, so it's called the line continuation character. It should only be followed by a newline, e.g.
>>> var1 = 'Ahmed' + \
'Ashraf'
If it's followed by some other character, such as t in your example, you get an error.
You can also do it with the format string.
>>> '%s\t%s' %('Ahmed','Ashraf')
'Ahmed\tAshraf'
>>>

Python unexpected character after line continuation character

I am very new to Python. I am constructing a string that is nothing but a path to the network location as follows. But it outputs the error: "Python unexpected character after line continuation character". Please help. I saw this post but I am not sure if it applies to my scenario:
syntaxerror: "unexpected character after line continuation character in python" math
s_path_publish_folder = r"\\" + s_host + "\" + s_publish_folder "\" + s_release_name
One of your \ backslashes escapes the " double quote following it. The rest of the string then ends just before the next \ backslash, and that second backslash is seen as a line-continuation character. Because there's another " right after that you get your error:
s_path_publish_folder = r"\\" + s_host + "\" + s_publish_folder "\" + s_release_name
# ^^ not end of string ||
# ^--- actual string ---^||
# line continuation /|
# extra character /
You need to double those backslashes:
s_path_publish_folder = r"\\" + s_host + "\\" + s_publish_folder "\\" + s_release_name
Better yet, use the os.path module here; for example, you could use os.path.join():
s_path_publish_folder = r"\\" + os.path.join(s_host, s_publish_folder, s_release_name)
or you could use string templating:
s_path_publish_folder = r"\\{}\{}\{}".format(s_host, s_publish_folder, s_release_name)

Need a string with double quote immediately followed by single quote in python 2.6

I am trying to store a string in variable A which contains:
"'D:\\Work\\B1.tif';'D:\\Work\\B2.tif'"
I have two variables that store the locations of B1.tif and B2.tif:
X = "D:\\Work\\B1.tif"
Y = "D:\\Work\\B2.tif"
However, when I try to combine all the strings into a variable 'A':
A = '"' + "'" + X + "'" + ";" + "'" + Y + "'" + '"'
This is what it stores as:
'"\'D:\\Work\\B1.tif\';\'D:\\Work\\B2.tif\'"'
When I print A it displays:
"'D:\Work\B1.tif';'D:\Work\B2.tif'"
It seems that a backslash (\), that separates double quotes (") and single quotes ("), are automatically stored in the string. How do I store double quotes and single quotes in a string without the backslash separating the quotes?
print '"\'%s\';\'%s\'"' %(X,Y)
String formatting (and raw strings) is much easier:
A = "\"'D:\\Work\\B1.tif';'D:\\Work\\B1.tif'\""
print A
X = r"D:\Work\B1.tif"
Y = r"D:\Work\B2.tif"
A = '"' + "'" + X + "'" + ";" + "'" + Y + "'" + '"'
print A
A = "\"'%s';'%s'\"" % (X, Y)
print A
Gives:
"'D:\Work\B1.tif';'D:\Work\B1.tif'"
"'D:\Work\B1.tif';'D:\Work\B2.tif'"
"'D:\Work\B1.tif';'D:\Work\B2.tif'"
However, to get the results you show, you have to use repr(), which is what IDLE uses if you just type the variable name in. If I change all the print statements to print repr(A) I get:
'"\'D:\\Work\\B1.tif\';\'D:\\Work\\B1.tif\'"'
'"\'D:\\Work\\B1.tif\';\'D:\\Work\\B2.tif\'"'
'"\'D:\\Work\\B1.tif\';\'D:\\Work\\B2.tif\'"'
IDLE uses the class's __repr__() method, print uses __str__(). Often they are the same, but sometime, as here, they are not.
When you display a variable in Python by just typing it's name, Python tries to print it in a way that if you were to copy and paste it as a variable, it would produce the same object. This works for strings, lists, dictionaries, sets, etc. The consequence is that strings need to be escaped when printed out this way. The backlashes are not actually stored in the string. You can see that by calculating the length:
>>> a = '"' + "'"
>>> a
'"\''
>>> len(a)
2
>>> print a
"'
There are, however, better ways to build the same string you want, as shown by the other answers.
Try using str.format() for these complicated formatting situations, you can even use triple quoted strings to make it easier.
A = ''' "'{}';'{}'" '''.format(X,Y)

syntaxerror: "unexpected character after line continuation character in python" math

I am having problems with this Python program I am creating to do maths, working out and so solutions but I'm getting the syntaxerror: "unexpected character after line continuation character in python"
this is my code
print("Length between sides: "+str((length*length)*2.6)+" \ 1.5 = "+str(((length*length)*2.6)\1.5)+" Units")
My problem is with \1.5 I have tried \1.5 but it doesn't work
Using python 2.7.2
The division operator is /, not \
The backslash \ is the line continuation character the error message is talking about, and after it, only newline characters/whitespace are allowed (before the next non-whitespace continues the "interrupted" line.
print "This is a very long string that doesn't fit" + \
"on a single line"
Outside of a string, a backslash can only appear in this way. For division, you want a slash: /.
If you want to write a verbatim backslash in a string, escape it by doubling it: "\\"
In your code, you're using it twice:
print("Length between sides: " + str((length*length)*2.6) +
" \ 1.5 = " + # inside a string; treated as literal
str(((length*length)*2.6)\1.5)+ # outside a string, treated as line cont
# character, but no newline follows -> Fail
" Units")
You must press enter after continuation character
Note: Space after continuation character leads to error
cost = {"apples": [3.5, 2.4, 2.3], "bananas": [1.2, 1.8]}
0.9 * average(cost["apples"]) + \ """enter here"""
0.1 * average(cost["bananas"])
The division operator is / rather than \.
Also, the backslash has a special meaning inside a Python string. Either escape it with another backslash:
"\\ 1.5 = "`
or use a raw string
r" \ 1.5 = "
Well, what do you try to do? If you want to use division, use "/" not "\".
If it is something else, explain it in a bit more detail, please.
As the others already mentioned: the division operator is / rather than **.
If you wanna print the ** character within a string you have to escape it:
print("foo \\")
# will print: foo \
I think to print the string you wanted I think you gonna need this code:
print("Length between sides: " + str((length*length)*2.6) + " \\ 1.5 = " + str(((length*length)*2.6)/1.5) + " Units")
And this one is a more readable version of the above (using the format method):
message = "Length between sides: {0} \\ 1.5 = {1} Units"
val1 = (length * length) * 2.6
val2 = ((length * length) * 2.6) / 1.5
print(message.format(val1, val2))
This is not related to the question; just for future purpose. In my case, I got this error message when using regex. Here is my code and the correction
text = "Hey I'm Kelly, how're you and how's it going?"
import re
When I got error:
x=re.search(r'('\w+)|(\w+'\w+)', text)
The correct code:
x=re.search(r"('\w+)|(\w+'\w+)", text)
I'm meant to use double quotes after the r instead of single quotes.

How can I strip first and last double quotes?

I want to strip double quotes from:
string = '"" " " ""\\1" " "" ""'
to obtain:
string = '" " " ""\\1" " "" "'
I tried to use rstrip, lstrip and strip('[^\"]|[\"$]') but it did not work.
How can I do this?
If the quotes you want to strip are always going to be "first and last" as you said, then you could simply use:
string = string[1:-1]
If you can't assume that all the strings you process have double quotes you can use something like this:
if string.startswith('"') and string.endswith('"'):
string = string[1:-1]
Edit:
I'm sure that you just used string as the variable name for exemplification here and in your real code it has a useful name, but I feel obliged to warn you that there is a module named string in the standard libraries. It's not loaded automatically, but if you ever use import string make sure your variable doesn't eclipse it.
IMPORTANT: I'm extending the question/answer to strip either single or double quotes. And I interpret the question to mean that BOTH quotes must be present, and matching, to perform the strip. Otherwise, the string is returned unchanged.
To "dequote" a string representation, that might have either single or double quotes around it (this is an extension of #tgray's answer):
def dequote(s):
"""
If a string has single or double quotes around it, remove them.
Make sure the pair of quotes match.
If a matching pair of quotes is not found,
or there are less than 2 characters, return the string unchanged.
"""
if (len(s) >= 2 and s[0] == s[-1]) and s.startswith(("'", '"')):
return s[1:-1]
return s
Explanation:
startswith can take a tuple, to match any of several alternatives. The reason for the DOUBLED parentheses (( and )) is so that we pass ONE parameter ("'", '"') to startswith(), to specify the permitted prefixes, rather than TWO parameters "'" and '"', which would be interpreted as a prefix and an (invalid) start position.
s[-1] is the last character in the string.
Testing:
print( dequote("\"he\"l'lo\"") )
print( dequote("'he\"l'lo'") )
print( dequote("he\"l'lo") )
print( dequote("'he\"l'lo\"") )
=>
he"l'lo
he"l'lo
he"l'lo
'he"l'lo"
(For me, regex expressions are non-obvious to read, so I didn't try to extend #Alex's answer.)
To remove the first and last characters, and in each case do the removal only if the character in question is a double quote:
import re
s = re.sub(r'^"|"$', '', s)
Note that the RE pattern is different than the one you had given, and the operation is sub ("substitute") with an empty replacement string (strip is a string method but does something pretty different from your requirements, as other answers have indicated).
If string is always as you show:
string[1:-1]
Almost done. Quoting from http://docs.python.org/library/stdtypes.html?highlight=strip#str.strip
The chars argument is a string
specifying the set of characters to be
removed.
[...]
The chars argument is not a prefix or
suffix; rather, all combinations of
its values are stripped:
So the argument is not a regexp.
>>> string = '"" " " ""\\1" " "" ""'
>>> string.strip('"')
' " " ""\\1" " "" '
>>>
Note, that this is not exactly what you requested, because it eats multiple quotes from both end of the string!
Remove a determinated string from start and end from a string.
s = '""Hello World""'
s.strip('""')
> 'Hello World'
Starting in Python 3.9, you can use removeprefix and removesuffix:
'"" " " ""\\1" " "" ""'.removeprefix('"').removesuffix('"')
# '" " " ""\\1" " "" "'
If you are sure there is a " at the beginning and at the end, which you want to remove, just do:
string = string[1:len(string)-1]
or
string = string[1:-1]
I have some code that needs to strip single or double quotes, and I can't simply ast.literal_eval it.
if len(arg) > 1 and arg[0] in ('"\'') and arg[-1] == arg[0]:
arg = arg[1:-1]
This is similar to ToolmakerSteve's answer, but it allows 0 length strings, and doesn't turn the single character " into an empty string.
in your example you could use strip but you have to provide the space
string = '"" " " ""\\1" " "" ""'
string.strip('" ') # output '\\1'
note the \' in the output is the standard python quotes for string output
the value of your variable is '\\1'
Below function will strip the empty spces and return the strings without quotes. If there are no quotes then it will return same string(stripped)
def removeQuote(str):
str = str.strip()
if re.search("^[\'\"].*[\'\"]$",str):
str = str[1:-1]
print("Removed Quotes",str)
else:
print("Same String",str)
return str
find the position of the first and the last " in your string
>>> s = '"" " " ""\\1" " "" ""'
>>> l = s.find('"')
>>> r = s.rfind('"')
>>> s[l+1:r]
'" " " ""\\1" " "" "'

Categories