Is it, in Python, possible to adress a specific character in a string by the standard array syntax?
Example, PHP:
$foo = 'bar';
echo $foo[1]; // Output: a
It didn't work like in PHP so I wanted to know if it is possible using some other way
Is it, in Python, possible to adress a specific character in a string by the standard array syntax?
Example, PHP:
$foo = 'bar';
echo $foo[1]; // Output: a
It didn't work like in PHP so I wanted to know if it is possible using some other way
As Adam pointed out, reading from a string array is possible in Python using the indexing syntax. What isn't possible though is writing to a string using this syntax:
>>> s = 'bar'
>>> s[2] = 'z'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
Maybe this was the problem you ran into?
Yes, this works. In fact, it works exactly like it does in PHP. The only difference is that variable names in Python are not preceeded by the $
character.
foo = 'bar'
print foo[1] # Output: a
Is Python, strings are one of a number of sequence types. You can find all of the operations that you can perform on sequence types in the Python documentation.