[Tutor] How to change the char in string for Python
davea at davea.name
Sun Feb 24 13:40:31 CET 2013
Both your later remarks are top-posted, ruining the sequence of who
On 02/24/2013 06:57 AM, Sudo Nohup wrote:
> Thanks for your help.
> I just found a webpage used for me:
> That page provides some other solutions. Thanks!
> On Sun, Feb 24, 2013 at 7:47 PM, Asokan Pichai <pasokan at talentsprint.com>wrote:
>> On Feb 24, 2013 4:27 PM, "Sudo Nohup" <sudo.nohup at gmail.com> wrote:
>>> Dear all,
>>> I want to change the value of a char in a string for Python. However, It
>> seems that "=" does not work.
assignment works fine, when it's really assignment. But it doesn't work
inside an expression, and you cannot change an immutable object in place.
>>> Could you help me? Thanks!
>>> str = "abcd"
>>> result = [char = 'a' for char in str if char == 'c']
In a list comprehension, the if expression is used to skip items from
the sequence. So the above form, modified, might be used to remove
selected characters from the string.
By the way, since 'str' is a builtin, it's a bad practice to take it
over for your own use. For example, what if you subsequently needed to
convert an int to a string?
>>> str = 'abcd'
>>> for char in str:
>>> if char == 'a':
>>> char = 'c'
You create a new object, and bind it to char, but then you don't do
anything with it.
>>> str = 'abcd'
>>> for i in range(len(str)):
>>> if str[i] == 'a':
>>> str[i] = 'c'
>>> Traceback (most recent call last):
>>> File "<stdin>", line 3, in <module>
>>> TypeError: 'str' object does not support item assignment
A string object is immutable, so that you cannot use assignment to
replace portions of it.
>> Look up string replace function.
That of course is the simplest answer to the problem as originally given.
(Here is where your amendment to the problem should have been given,
rather than top-posting it.)
But you now say you're planning to replace all the characters in the
string, according to a formula.
What yo should have specified in the first place is what version of
Python you're using. I'll assume 2.7
This amended problem would lend itself nicely to translate(), and the
link you posted does mention that.
But there are several other approaches, similar to the ones you already
tried, and sometimes one of them is more interesting or useful.
For example, a list comprehension very close to what you tried would
work fine (untested):
temp = [ chr( ord(char) + 2 ) for char in mystring]
result = "".join(temp)
Likewise a loop:
result = 
for char in mystring:
char = chr ( ord(char) + 2
result = "".join(result)
More information about the Tutor