Why str([1]) = [1] and not "1" in python - python

str([1]) = [1]
If we apply type conversion on the str([1]), why don't we get the answer = "1".

There is no type conversion here. str is a builtin function that takes any object, and produces a string representation of it (typically using the __str__ method of the object).
Here, the argument to str is a list [1], and the __str__ method of list converts its elements to strings (using repr), joins them with commas, and surrounds them with square brackets [].

first of all use str() in python ;)
str cast the parameter you give into a string. So when the parameter is an array, it returns you "[1]". You can see the type of the result with type(param), it'll be a string and if you print res[0] it'll give you "["
If you wanna get ride of the [] you can use the code bellow for example :
print(s.replace('[', '').replace(']', ''))

Related

How to convert an entire list of strings to a normal array or list?

I have a variable which is a = '"[200.0', ' 100.0]"'. While trying to access individual element like a[0] = '"[200.0'
The data type of this I checked says tuple. This is not the format I can work on, hence I want to convert this to a simple list/array like the following format for ex:
a = [200.0,100.0] .So that a[0] = 200.0 which could be either float or int data type.
I have tried using literal_eval, eval but it keeps throwing an error. A workable solution would be really helpful. Any ideas for this?
You can do it with regex to clean the a string from unwanted characters and then split it by the , to be a list
import re
a = '"[200.0', ' 100.0]"'
a = [re.sub(r"""["'\[\] ]""", "",i) for i in a]
print(a)
Output
['200.0', '100.0']
OR if you want it to be from float type
a = [float(re.sub(r"""["'\[\] ]""", "",i)) for i in a]
print(a)
Output
[200.0, 100.0]
Just for fun, you could also try this:
my_list = eval(eval(",".join(a)))
Explanation:
",".join(a) produces a single string '"[200.0, 100.0]"'
Calling eval() on this strips away the outer single-quotes, producing "[200.0, 100.0]" (that's a string containing [ as the first character and ] as the last)
Calling eval() again on this evaluates the above string, producing [200.0, 100.0], which gets assigned to my_list as a proper list object

Strings are lists but i cannot use list methods on them like append or replace. Why?

I'm a beginner and I'm trying to make a palindrome from a user input. I was thinking I could use .replace() but I got an error that 'str' object has no attribute 'append'. I thought strings were lists? So why don't list methods work on them?
Strings are not lists, they are sequences. They share some of the same behaviors as lists, but they are not themselves lists. Strings are immutable objects.
You can convert a string to a list by passing the string to list:
data = list("some string")
You can then operate on data, and convert it back to a string later with join:
new_string = "".join(data)
If you simply want to add a character to a string you can use concatenation:
new_string = "abc" + "d"
Strings are a distinct class from Lists. As the error says, Strings don't have an append method.
append wouldn't make sense for Strings anyways, as they're immutable. They can't be modified in place like lists can.
If you want to "append" a Character, just use concatenation, and reassign the String:
x = "String" + "s"
Tl;dr: strings != lists.
You can index individual characters in strings, like you can index elements in lists, but there is a difference in mutability.
If something is mutable, it can change. Lists are mutable so you can change the contents of them (either adding, removing or changing elements).
See some examples that I am sure you are familiar with:
>>> l = [1, 2, 3]
>>> l[0] = 9
>>> l.append(8)
>>> l
[9, 2, 3, 8]
On the other hand, strings are immutable so can not change. This means that there are no append or equivalent methods. However, you can concatenate two of them to form a new string, but this is a different operation in terms of memory (appending modifies the current space in memory, concatenation assigns a whole new space in memory to the new string).
So here are some examples with strings:
>>> s = "abcdef"
>>> s += "ghi"
>>> s
'abcdefghi'
>>> s[0] = "z"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
To get things clear, str and list are two different data types.
One basic difference between str's and lists is that lists can any type of data i.e. integers, characters, dictionary or another list etc., while strings can only hold a set of characters(alphabets numbers or any special characters).
Also, lists are mutable and string are immutable!
Reference.
To get to know what methods can be used with a string dir(str) and dir(list) would help!
You can use Python's type() method to figure out what type the object is:
>>> type("String")
<class 'str'>
You can also turn the string into a list using the list method:
>>> type(list("String"))
<class 'list'>

Why single element tuple is interpreted as that element in python?

Could anyone explain why single element tuple is interpreted as that element in Python?
And
Why don't they just print the tuple (1,) as (1)?
See the examples below:
>>> (1)
1
>>> ((((1))))
1
>>> print(1,)
1
>>> print((1,))
(1,)
It's because (1) is not a tuple. (1) is 1 with parentheses surrounding it. As the python documentation states
it is the comma, not the parentheses, that define the tuple.
Source
The only tuple without a comma is a 0-tuple, which is (). Note, you can check this by running type((1)) and seeing that it returns <type 'int'> not <type 'tuple'>.
A single element tuple is never treated as the contained element. Parentheses are mostly useful for grouping, not for creating tuples; a comma does that.
Why don't they just print (1,) as (1)?
Probably because printing a builtin container type gives a representation that can be used to recreate the container object via , say eval:
The docs for __repr__ provides some clarity on this:
If at all possible, this should look like a valid Python expression
that could be used to recreate an object with the same value
Answering your question, (1) is just integer 1 with a grouping parenthesis. In order to recreate the singleton tuple via its representation, it has to be printed as (1,) which is the valid syntax for creating the tuple.
>>> t = '(1,)'
>>> i = '(1)'
>>> eval(t)
(1,) # tuple
>>> eval(i)
1 # int
Because only (1, ) in your examples is tuple. The rest are expressions.
In [4]: type(1,)
Out[4]: int
In [5]: type((1,))
Out[5]: tuple
In [6]: type((1))
Out[6]: int
This is very detailed answer from #Ray Total
Sure, in general parentheses don't change the meaning of an expression. For example you can say 4+(1) and it will be 5, the same way 4*(2-1) would be 4. Because the convention is to use parentheses for grouping of subexpressions, the designer of Python thought it would be too confusing to overload the meaning to mean both grouping and single-element tuples. Also Python has a type function. In fact type((2)) is int and type((2,)) is tuple. We don't want there to be any ambiguity, which there would be if (2) were treated as a tuple
A tuple consists of a number of values separated by commas (not necessary parentheses).
You can even define tuple like this
t = 1, # (with or without surrounding parentheses)
>>> type(t)
<class 'tuple'>
Here , used to tell interpreter to create tuple if not present it will consider as int.
Same rule applies when we define like this
>>> t = (1)
>>> type(t)
<class 'int'>
(1) is not a tuple, it's just parentheses around a number. This is because sometimes you want to use parentheses to indicate order of operations, for example: (x+y)*z. This obviously doesn't refer to a tuple containing x+y, it's just to show that the addition should happen before the multiplication.
(((1))) is not a tuple for the same reason, the parentheses are just saying "evaluate what's inside before moving on".
print(1,) is just calling the print function on the number 1. When calling a function, a trailing comma is allowed. However, in python2, this will probably pring (1,), because print isn't a function.
print((1,)) is the only thing that prints a tuple, because we are now actually passing a tuple into the function.

Python:Can anybody explain me this one line code?

print(''.join(map(str,range(1,n+1))))
Like what is str doing here ? and how is this outputting in the single line ?i know what map and join does but still i'm not clear with this whole code
numbers_one_to_n = range(1,n+1)
numbers_as_strings = map(str, numbers_one_to_n)
numbers_joined_to_single_string = ''.join(numbers_as_strings)
print(numbers_joined_to_single_string)
print(''.join(map(str,range(1,n+1))))
You say you know what map does? The documentation says:
map(function, iterable, ...)
Return an iterator that applies function to every item of iterable, yielding the result.
So str is the function. The iterable is the range of integers (in Python 3 this is a range object`)
str returns a string object generated from its argument.
So, str is called for each integer in the range.
An alternative to map is a list comprehension, which some prefer:
print(''.join([str(i) for i in range(1,n+1)]))
'' is a separator, that used between the concatenating elements (strings in a string sequence or characters in a string). For instance:
>>> '-'.join(('foo', 'bar'))
'foo-bar'
>>> '-'.join('bar')
'b-a-r'
str is a type and the function to convert to this type.
So, map(str, list_of_integers) converts this list to a list of strings. Because map applies the function to each element of input list to get output list.
So, we have the range from 1 to (n + 1), that have been converted to the list of the strings, and then this list have been concatenated with the empty slitter ''.

Python string converts magically to tuple. Why?

I've got a dict in which I load some info, among others a name which is a plain string. But somehow, when I assign it to a key in the dict it gets converted to a tuple, and I have no idea why.
Here's some of my code:
sentTo = str(sentTo)
print type(sentTo), sentTo
ticketJson['sentTo'] = sentTo,
print type(ticketJson['sentTo']), ticketJson['sentTo']
which outputs the following on my terminal:
<type 'str'> Pete Chasin
<type 'tuple'> ('Pete Chasin',)
Why does assigning it to a dict convert it to a tuple?
You told Python to create a tuple containing a string:
ticketJson['sentTo'] = sentTo,
# ^
It is the comma that defines a tuple. Parentheses are only needed to disambiguate a tuple from other uses of a comma, such as in a function call.
From the Parenthesized forms section:
Note that tuples are not formed by the parentheses, but rather by use of the comma operator. The exception is the empty tuple, for which parentheses are required — allowing unparenthesized “nothing” in expressions would cause ambiguities and allow common typos to pass uncaught.
and from Expression lists:
An expression list containing at least one comma yields a tuple. The length of the tuple is the number of expressions in the list. The expressions are evaluated from left to right.
ticketJson['sentTo'] = sentTo, is single element tuple

Categories

Resources