Don't use a string, use something mutable like bytearray:
#!/usr/bin/python
s = bytearray("my dog has fleas")
for n in xrange(len(s)):
s[n] = chr(s[n]).upper()
print s
Results in:
MY DOG HAS FLEAS
Edit:
Since this is a bytearray, you aren't (necessarily) working with characters. You're working with bytes. So this works too:
s = bytearray("\x81\x82\x83")
for n in xrange(len(s)):
s[n] = s[n] + 1
print repr(s)
gives:
bytearray(b'\x82\x83\x84')
If you want to modify characters in a Unicode string, you'd maybe want to work with memoryview, though that doesn't support Unicode directly.
Don't use a string, use something mutable like bytearray:
#!/usr/bin/python
s = bytearray("my dog has fleas")
for n in xrange(len(s)):
s[n] = chr(s[n]).upper()
print s
Results in:
MY DOG HAS FLEAS
Edit:
Since this is a bytearray, you aren't (necessarily) working with characters. You're working with bytes. So this works too:
s = bytearray("\x81\x82\x83")
for n in xrange(len(s)):
s[n] = s[n] + 1
print repr(s)
gives:
bytearray(b'\x82\x83\x84')
If you want to modify characters in a Unicode string, you'd maybe want to work with memoryview, though that doesn't support Unicode directly.
The Python analog of your C:
for(int i = 0; i < strlen(s); i++)
{
s[i] = F(s[i]);
}
would be:
s = "".join(F(c) for c in s)
which is also very expressive. It says exactly what is happening, but in a functional style rather than a procedural style.
Using replace() method
Selective replacement of matching text in a string?
Hello, is there a way to mutate strings in Python?
Finding and replacing specific placeholders in a text file
Videos
Hi guys, I had a quick question about the exercise I was working on.
For using the replace() method and printing the result, we have to assign it to another variable and print that new variable.
sentence = sentence.replace(‘hey’, ‘hi’) print(sentence)
But for something such as the sort method we don’t need to assign it to a new variable and just use it straight up.
list = […] list.sort() print(list)
Why is it that some methods you need to assign it to a new variable, while others work while not assigning it to a new variable and the original is changed. Thank you.
Sorry about format, I’m on mobile.