back slash in token key [duplicate] - python

In Python, when I print a string with a backslash, it prints the backslash only once:
>>> print(r'C:\hi')
C:\hi
>>> print('C:\\hi')
C:\hi
But I noticed that when you print a tuple of strings with backslashes, it prints a double backslash:
>>> print((r'C:\hi', 'C:\\there'))
('C:\\hi', 'C:\\there')
Why does it behave differently when printing the tuple?
(Note, this happens in both Python 2 and 3, and in both Windows and Linux.)

When you print a tuple (or a list, or many other kinds of items), the representation (repr()) of the contained items is printed, rather than the string value. For simpler types, the representation is generally what you'd have to type into Python to obtain the value. This allows you to more easily distinguish the items in the container from the punctuation separating them, and also to discern their types. (Think: is (1, 2, 3) a tuple of three integers, or a tuple of a string "1, 2" and an integer 3—or some other combination of values?)
To see the repr() of any string:
print(repr(r'C:\hi'))
At the interactive Python prompt, just specifying any value (or variable, or expression) prints its repr().
To print the contents of tuples as regular strings, try something like:
items = (r'C:\hi', 'C:\\there')
print(*items, sep=", ")
str.join() is also useful, especially when you are not printing but instead building a string which you will later use for something else:
text = ", ".join(items)
However, the items must be strings already (join requires this). If they're not all strings, you can do:
text = ", ".join(map(str, items))

Related

how to assign string input as list in python

User is giving list as input [1,2,3,4]:
a = input()
It is taking this as str.
I want to get this data into local list b.
b = a.strip('][').split(', ')
print(b)
Output: ['1,2,3,4']
How to get list individually not a single entity?
You should do .split(',') instead of .split(', ')
You can use ast.literal_eval to do so.
import ast
a = input()
b = ast.literal_eval(a)
print(b)
# output
[1, 2, 3, 4]
From the docs:
Safely evaluate an expression node or a string containing a Python
literal or container display. The string or node provided may only
consist of the following Python literal structures: strings, bytes,
numbers, tuples, lists, dicts, sets, booleans, None and Ellipsis.
This can be used for safely evaluating strings containing Python
values from untrusted sources without the need to parse the values
oneself. It is not capable of evaluating arbitrarily complex
expressions, for example involving operators or indexing.
the problem is that in the line:
b = a.strip('][').split(', ')
you used ', ' with whitespace instead of ',' without whitespace
because your input does not have any spaces as shown below:
user is giving list as input [1,2,3,4]
ast.literal_eval(a) gets the string input as a list datatype, which can be converted into a list of individual strings with map:
import ast
b = list(map(str,ast.literal_eval(a)))
['1', '2', '3', '4']

How i can replace in a list of strings "\\" with "\" in Python

In my code i have a list of locations and the output of a list is like this
['D:\\Todo\\VLC\\Daft_Punk\\One_more_time.mp4"', ...
i want a replace "\\" with "\"
(listcancion is a list with all strings)
i try to remplace with this code remplacement = [listcancion.replace('\\', '\') for listcancion in listcancion] or this remplacement = [listcancion.replace('\\\\', '\\') for listcancion in listcancion] or also this remplacement = [listcancion.replace('\\', 'X') for listcancion in listcancion]
listrandom = [remplacement.replace('X', '\') for remplacement in remplacement]
I need to change only the character \ i can't do it things like this ("\\Todo", "\Todo") because i have more characters to remplace.
If i can solved without imports thats great.
It is just a matter of string representations.
First, you have to differentiate between a string's "real" content and its representation.
A string's "real" content might be letters, digits, punctuation and so on, which makes displaying it quite easy. But imagine a strring which contains a, a line break and a b. If you print that string, you get the output
a
b
which is what you expect.
But in order to make it more compact, this string's representation is a\nb: the line break is represented as \n, the \ serving as an escape character. Compare the output of print(a) (which is the same as print(str(a))) and of print(repr(a)).
Now, in order not to confuse this with a string which contains a, \, n and b, a "real" backslash in a string has a representation of \\ and the same string, which prints as a\nb, has a representation of a\\nb in order to distinguish that from the first example.
If you print a list of anything, it is displayed as a comma-separated list of the representations of their components, even if they are strings.
If you do
for element in listcancion:
print(element)
you'll see that the string actually contains only one \ where its representation shows \\.
(Oh, and BTW, I am not sure that things like [listcancion.<something> for listcancion in listcancion] work as intended; better use another variable as the loop variablen, such as [element.<something> for element in listcancion].)

japanese, korean characters not showing up in lists, but show up fine when printed separately

I have strings of characters in different languages, mainly Japanese, and they show up fine when I try to print them as strings. However, when I add many of them to a python list, and then print out the list, they display as text like this: xe9
for example:
string1 = "西野カナ- NO. 1"
string2 = "첫눈처럼 너에게 가겠다"
list1 = []
list1.append(string1)
list1.append(string2)
print list1
for item in list1:
print item
These two prints will give me different outputs:
['\xe8\xa5\xbf\xe9\x87\x8e\xe3\x82\xab\xe3\x83\x8a- NO. 1 NEW', '\xec\xb2\xab\xeb\x88\x88\xec\xb2\x98\xeb\x9f\xbc \xeb\x84\x88\xec\x97\x90\xea\xb2\x8c \xea\xb0\x80\xea\xb2\xa0\xeb\x8b\xa4']
西野カナ- NO. 1 NEW
첫눈처럼 너에게 가겠다
How would I get the list to print the actual characters too?
Actually,when you print a list or write to a file, it internally calls the str() method,and list internally calls repr() on its elements. So you are seeing is repr() returns.
print repr(string1)
'\xe8\xa5\xbf\xe9\x87\x8e\xe3\x82\xab\xe3\x83\x8a- NO. 1'
It is really discouraged.So if you want to avoid encoding problem, you should start to think seriously about switching to Python3.
You can check out this or see unicode in python2 and python3

Find Certain String Indices

I have this string and I need to get a specific number out of it.
E.G. encrypted = "10134585588147, 3847183463814, 18517461398"
How would I pull out only the second integer out of the string?
You are looking for the "split" method. Turn a string into a list by specifying a smaller part of the string on which to split.
>>> encrypted = '10134585588147, 3847183463814, 18517461398'
>>> encrypted_list = encrypted.split(', ')
>>> encrypted_list
['10134585588147', '3847183463814', '18517461398']
>>> encrypted_list[1]
'3847183463814'
>>> encrypted_list[-1]
'18517461398'
Then you can just access the indices as normal. Note that lists can be indexed forwards or backwards. By providing a negative index, we count from the right rather than the left, selecting the last index (without any idea how big the list is). Note this will produce IndexError if the list is empty, though. If you use Jon's method (below), there will always be at least one index in the list unless the string you start with is itself empty.
Edited to add:
What Jon is pointing out in the comment is that if you are not sure if the string will be well-formatted (e.g., always separated by exactly one comma followed by exactly one space), then you can replace all the commas with spaces (encrypt.replace(',', ' ')), then call split without arguments, which will split on any number of whitespace characters. As usual, you can chain these together:
encrypted.replace(',', ' ').split()

Printing a string prints 'u' before the string in Python?

'u' before elements in printed list? I didn't type u in my code.
hobbies = []
#prompt user three times for hobbies
for i in range(3):
hobby = raw_input('Enter a hobby:')
hobbies.append(hobby)
#print list stored in hobbies
print hobbies
When I run this, it prints the list but it is formatted like this:
Enter a hobby: Painting
Enter a hobby: Stargazing
Enter a hobby: Reading
[u'Painting', u'Stargazing', u'Reading']
None
Where did those 'u' come from before each of the elements of the list?
I think what you're actually surprised by here is that printing a single string doesn't do the same thing as printing a list of strings—and this is true whether they're Unicode or not:
>>> hobby1 = u'Dizziness'
>>> hobby2 = u'Vértigo'
>>> hobbies = [hobby1, hobby2]
>>> print hobby1
Dizziness
>>> print hobbies
[u'Dizziness', u'V\xe9rtigo']
Even without the u, you've got those extra quotes, not to mention that backslash escape. And if you try the same thing with str byte strings instead of unicode strings, you'll still have the quotes and escapes (plus you might have mojibake characters if your source file and your terminal have different encodings… but forget that part).
In Python, every object can have two different representations: the end-user-friendly representation, str, and the programmer-friendly representation, repr. For byte strings, those representations are Painting and 'Painting', respectively. And for Unicode strings, they're Painting and u'Painting'.
The print statement uses the str, so print hobby1 prints out Painting, with no quotes (or u, if it's Unicode).
However, the str of a list uses the repr of each of its elements, not the str. So, when you print hobbies, each element has quotes around it (and a u if it's Unicode).
This may seem weird at first, but it's an intentional design decision, and it makes sense once you get used to it. And it would be ambiguous to print out [foo, bar, baz]—is that a list of three strings, or a list of two strings, one of which has a comma in the middle of it? But, more importantly, a list is already not a user-friendly thing, no matter how you print it out. My hobbies are [Painting, Stargazing] would look just as ugly as My hobbies are ['Painting', 'Stargazing']. When you want to show a list to an end-user, you always want to format it explicitly in some way that makes sense.
Often, what you want is as simple as this:
>>> print 'Hobbies:', ', '.join(hobbies)
Hobbies: Painting, Stargazing
Or, for Unicode strings:
>>> print u'Hobbies:', u', '.join(hobbies)
Hobbies: Painting, Stargazing
The 'u' is not part of the string, but indicates that the string is a unicode string.
You're not printing the strings, you're printing the representation of the list holding the strings.
for hobby in hobbies:
print hobby
If you want to convert the unicode to string. You can simply use
str(unicodedString) or unicode(normalString) for the other way conversion
Code
hobbies = []
#prompt user three times for hobbies
for i in range(3):
hobby = raw_input('Enter a hobby:')
# converting the normal string to unicode
hobbies.append(unicode(hobby))
# Printing the unicoded string
print("Unicoded string")
print(hobbies)
hobbies = [str(items) for items in hobbies]
# Printing the converted string
print("Normal string from unicoded string")
print(hobbies)
Output
Enter a hobby:test1
Enter a hobby:Test2
Enter a hobby:Test3
Unicoded string
[u'test1', u'Test2', u'Test3']
Normal string from unicoded string
['test1', 'Test2', 'Test3']

Categories

Resources