简体   繁体   中英

How to replace string character in Python?

for i  in range(len(contents)):
    contents = contents.replace(contents[i],chr(ord(contents[i]) + 1)) 
print(contents)
for i in range(len(contents)):
    contents = contents.replace(contents[i],chr(ord(contents[i]) - 1))
print(contents)

This is where I get confused, shouldn't it just add 1 int to the character more and give you a character that is one byte (in UNICODE) above? Shouldn't it after you subtract one give you back the same result as before?

I have a string This is some sample text! . When I run the code, the string is converted to Ukkz%kz%zqoh%zboqmh%zhzz% .

Then, it should decrypt it back, but it show Tees es sole salole sess .

Thanks to @Jon Clements i have found a fix:

I converted the string into an array, then looped trough the array adding 1 to the character ordinal.

s = list(contents)

def encrypt(s):
    for i  in range(len(s)):
        s[i] = chr(ord(s[i]) + 1)
    ret = ''.join(s)
    return ret
contents = "This is some sample text!"
print(f"Original value of contents: {contents}")
for i  in range(len(contents)):
    contents = contents[:i]+contents[i:].replace(contents[i],chr(ord(contents[i]) + 1),1)
print(f"Modified value of contents: {contents}")
for i  in range(len(contents)):       
    contents = contents[:i]+contents[i:].replace(contents[i],chr(ord(contents[i]) - 1),1)
print(f"Reversed value of contents: {contents}")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM