I am new to python,i like to print my string with out considering its special character(i mean raw string)
eg: >>> print 'Hello/npython/tworld'` when i print this its should give o/p as below
'Hello\npython\tworld'
How can i make my string as raw string
Thanks
Hema
Use repr(mystring) but this will not work if you intend to print with double quotes if initialized that way. It will always use single quotes.
Related
there are characters like '' that are not visible so I cant copy paste it. I want to convert any character to its codepoint like '\u200D'
another example is: 'abc' => '\u0061\u0062\u0063'
Allow me to rephrase your question. The header convert a string to its codepoint in python clearly did not get through to everyone, mostly, I think, because we can't imagine what you want it for.
What you want is a string containing a representation of Unicode escapes.
You can do that this way:
print(''.join("\\u{:04x}".format(b) for b in b'abc'))
\u0061\u0062\u0063
If you display that printed value as a string literal you will see doubled backslashes, because backslashes have to be escaped in a Python string. So it will look like this:
'\\u0061\\u0062\\u0063'
The reason for that is that if you simply put unescaped backslashes in your string literal, like this:
a = "\u0061\u0062\u0063"
when you display a at the prompt you will get:
>>> a
'abc'
'\u0061\u0062\u0063'.encode('utf-8') will encode the text to Unicode.
Edit:
Since python automatically converts the string to Unicode you can't see the value but you can create a function that will generate that.
def get_string_unicode(string_to_convert):
res = ''
for letter in string_to_convert:
res += '\\u' + (hex(ord(letter))[2:]).zfill(4)
return res
Result:
>>> get_string_unicode('abc')
'\\u0061\\u0062\\u0063'
I am new to Python and I am working to calculate checksum of a string that has backslashes (). I was able to come up with a logic to calculate the checksum but that function needs the string to be in raw format (r') to calculate the correct checksum. However this function will be invoked by another function and I will not be able to convert the string to raw string manually. Can someone please help me on how to achieve this dynamically.
Here is the string:
raw_message1 = '=K+8\\\08|'
This string has 3 backslashes however it shows only 2 after saving and this string may vary again so replacing after processing will not help.
And when I print the result:
print(message1)
=K+8\ 8|
What I need is to have something that retains the backslashes as is. I cannot go for any other character as every character has its own ASCII value and checksum would differ. I tried all the other options mentioned before and see different result for each case.
You can define the string as so:
message1 = r'=K+8\\08|'
This should make the string message1 be in raw form.
Let me know if this helps. I don't really understand what you mean by converting to raw string manually and converting it dynamically. This is the most I can help with for now.
All the r prefix does is manually add backslashes so you don't have to, it doesn't "magically" retain the backslashes, instead it replaces them with double backslashes so they are interpreted as single backslashes.
Look at the following example:
>>> s = r"\rando\\\mst\ri\ngo\\flet\ters"
>>> s
'\\rando\\\\\\mst\\ri\\ngo\\\\flet\\ters'
>>> print(s)
\rando\\\mst\ri\ngo\\flet\ters
>>>
The string actually contains double backslashes and when printed they are interpreted as single backslashes.
I am trying to use python format method to do format my placeholder in a string.
The issue is the string contains {} internally and the string method is unable to resolve it.
my_value='v'
'{"k":"{value}"}'.format(value=my_value) # This results in error due to outside {}
# Desired Output '{"k":"v"}'
How would I resolve this ?
I can convert this to json and then substitute but I prefer if the string format can do it
You don't need to override something, you can just escape the curly brackets by doubling them, as stated in the documentation for the format string syntax:
If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}.
>>> '{{"k":"{value}"}}'.format(value=my_value)
'{"k":"v"}'
This equally applies for formatted string literals if you plan on using them at some point:
>>> f'{{"k": "{my_value}"}}'
'{"k": "v"}'
Hi I am having trouble trying to print a literal string in a proper format.
For starters i have an object with a string parameter which is used for metadata such that it looks like:
obj {
metadata: <str>
}
The object is being returned as a protocol response and we have the object to use as such.
print obj gives:
metadata: "\n)\n\022foobar"
When I print the obj.metadata python treats the value as a string and converts the escapes to linebreaks and the corresponding ascii values as expected.
When i tried
print repr(obj.metadata)
"\n)\n\x12foobar"
Unfortunately python prints the literal but converts the escaped characters from octal to hex. Is there a way i can print the python literal with the escaped characters in octal or convert the string such that I can have the values printed as it is in the object?
Thanks for the help
The extremely bad solution I have so far is
print str(obj).rstrip('\"').lstrip('metadata: \"')
to get the correct answer, but i am assuming there must be a smarter way
TLDR:
x = "\n)\n\022foobar"
print x
)
foobar
print repr(x)
'\n)\n\x12foobar'
how do i get x to print the way it was assigned
Please try this:
print('\\\n)\\\n\\\022foobar')
or
print(r'\n)\n\022foobar')
The escape character '\' interprets the character following it differently, for example \n is used for new line.
The double escape character '\\' or letter 'r' nullifies the interpretation of the escape character. This is similar in C language.
I have a dictionary with some strings, in one of the string there are two backslashes. I want to replace them with a single backslash.
These are the backslashes: IfNotExist\\u003dtrue
Configurations = {
"javax.jdo.option.ConnectionUserName": "test",
"javax.jdo.option.ConnectionDriverName": "org.mariadb.jdbc.Driver",
"javax.jdo.option.ConnectionPassword": "sxxxsasdsasad",
"javax.jdo.option.ConnectionURL": "jdbc:mysql://hive-metastore.cr.eu-west-1.rds.amazonaws.com:3306/hive?createDatabaseIfNotExist\\u003dtrue"
}
print (Configurations)
When I print it keeps showing the two backslashes. I know that the way to escape a backslash is using \ this works in a regular string but it does not work in a dictionary.
Any ideas?
The problem comes from the encoding.
In fact \u003d is the UNICODE representation of =.
The backslash is escaped by another backslash which is a good thing.
You may need to:
Replace \u003d as =
Read it as unicode then you should prepend the string with u like u"hi \\u003d" may be ok
Printing the dictionary shows you a representation of the dictionary object. It doesn't necessarily show you a nice representation of everything inside it. To do that you need to do:
for value in Configurations.values():
print(value)
When you print out your dictionary using
print (Configurations), it will print out the repr() value of the dictionary
You will get
{'javax.jdo.option.ConnectionDriverName': 'org.mariadb.jdbc.Driver', 'javax.jdo.option.ConnectionUserName': 'test', 'javax.jdo.option.ConnectionPassword': 'sxxxsasdsasad', 'javax.jdo.option.ConnectionURL': 'jdbc:mysql://hive-metastore.cr.eu-west-1.rds.amazonaws.com:3306/hive?createDatabaseIfNotExist\\u003dtrue'}
You need to print out your dictionary with
print (Configurations["javax.jdo.option.ConnectionURL"])
or
print (str(Configurations["javax.jdo.option.ConnectionURL"]))
Note: str() is added
Then the output will be
jdbc:mysql://hive-metastore.cr.eu-west-1.rds.amazonaws.com:3306/hive?createDatabaseIfNotExist\u003dtrue
For more detail check Python Documentation - Fancier Output Formatting
The str() function is meant to return representations of values which
are fairly human-readable, while repr() is meant to generate
representations which can be read by the interpreter (or will force a
SyntaxError if there is no equivalent syntax).
If you want to represent that string by using a single backslash instead of a double backslash, then you need the str() representation, not the repr(). When you print a dictionary, you always get the repr() of the included strings.
You can print the str() by formatting the dictionary yourself, like so:
print ( "{" +
', '.join("'{key}': '{value}'".format(key=key, value=value)
for key, value in Configurations.items()) +
"}")
Depending on how you print your string, Python will print two backslashes where the string actually only has one in it. This is Python's way of indicating that the backslash is an actual backslash, and not part of an escaped character; because print will actually show you '\n' for a carriage return, for example.
Try writing the string to a file and then opening the file in an editor.
(Linux..)
> f = open('/tmp/somefile.txt', 'w')
> f.write(sometextwithbackslashes)
> \d
$ vi /tmp/somefile.txt