博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python modify string in place
阅读量:4030 次
发布时间:2019-05-24

本文共 5703 字,大约阅读时间需要 19 分钟。

In Python, strings are immutable.

What is the standard idiom to walk through a string character-by-character and modify it?

The only methods I can think of are some genuinely stanky hacks related to joining against a result string.

--

In C:

for(int i = 0; i < strlen(s); i++){   s[i] = F(s[i]);}

This is super expressive and says exactly what I am doing. That is what I am looking for. 

 
 
I guess since they are immutable you can't "modify it"... do you mean constructing a new string char-by-char?–   
Aug 12 '10 at 0:02
 
This is really rare. Can you give a context or a use case for doing this? –   
Aug 12 '10 at 0:21
 
Adding noise to a message for testing. –   
Aug 12 '10 at 0:22
 
@Paul Nathan: "Adding noise to a message"? As in "replacing characters at random"? What's wrong with replace for this? –   
Aug 12 '10 at 2:43
 
@S.Lott: Replace selects against pre-known elements in the list ``mystring.replace("1", "i")`; whereas I want to iterate by index - I don't know what elements will be in the list per se. (Why does this have to be such a pain?)–   
Aug 12 '10 at 5:51

12 Answers

12

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.

 
 
Interesting; I sort of like it, except for the null string. Probably as good as I'm getting though. – 
Aug 12 '10 at 0:35
1  
A significant part of the C to me is that it works in-place. –   
Aug 12 '10 at 7:33
 
@Joe Koberg: A significant part of the Python is that it's shorter and more clear. "in place" is limiting because you can't make the string longer. –   
Aug 12 '10 at 10:12
 
I understand that, but the OP seemed to be focusing on it. And rejected many standard python string transformation methods. That it didn't work in-place was the only thing left. –   
Aug 12 '10 at 15:26
 
Isn't map() the same as the list comprehension and join? –   
Aug 12 '10 at 20:53
11

Don't use a string, use something mutable like bytearray:

#!/usr/bin/pythons = 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] + 1print 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 , though that doesn't support Unicode directly.

 
2  
They aren't Characters, however, just bytes. Works only for ASCII, not Unicode. –   
Aug 12 '10 at 0:20
1  
Works for valid bytes, not just ASCII. –   
Aug 12 '10 at 0:30
9

you can use the UserString module:

>>> import UserString... s = UserString.MutableString('Python')... print sPython>>> s[0] = 'c'>>> print scython
 
1  
Note that MutableString was deprecated in Python 2.6 and removed in Python 3 - –   
Dec 8 '14 at 15:28
6

I'd say the most Pythonic way is to use :

s = map(func, s) # func has been applied to every character in s

This is the equivalent of writing:

s = "".join(func(c) for c in s)
 
1  
Minor correction/point: One still needs to re-join the returned list (/iter/map-obj in Py3+). So the above should be:  s = "".join(map(func, s)) –   
Apr 3 '13 at 20:54 
1

Strings are iterable and can be walked through like lists. Strings also have a number of basic methods such as .replace() that might be what you're looking for. All string methods return a new string. So instead of modifying the string in place you can simply replace its existing value.

>>> mystring = 'robot drama'>>> mystring = mystring.replace('r', 'g')>>> mystring'gobot dgama'
 
 
Strings are immutable and cannot be assigned to by member. –   
Aug 11 '10 at 23:58
 
Correct. All string operations return a copy of the input string. The variable name is NOT immutable, however, so by re-assigning a string operation to the same variable name, you are effectively "mutating" the string. –   
Aug 12 '10 at 0:00
 
"In the gage case of altegations to a stging, which do not incgease og decgease its length, it would still be useful if one could use the slice notation fog in-place adjustments: myStr[0:3][:] = 'new'".replace("g","r") –   
Aug 20 '15 at 20:00 
1
>>> mystring = "Th1s 1s my str1ng">>> mystring.replace("1", "i")'This is my string'

If you want to store this new string you'll have to mystring = mystring.replace("1", "i"). This is because in Python strings are immutable.

 
 
1: Don't use "string" as a variable name. 2: That doesn't modify the variable. –   
Aug 11 '10 at 23:58
 
That doesn't select by index and modify it. –   
Aug 12 '10 at 0:00
 
@bstpierre: There you go. :) –   
Aug 12 '10 at 0:01 
 
@Paul Nathan: Where was "by index" a requirement? –   
Aug 12 '10 at 0:19
1

Assigning a particular character to a particular index in a string is not a particularly common operation, so if you find yourself needing to do it, think about whether there may be a better way to accomplish the task. But if you do need to, probably the most standard way would be to convert the string to a list, make your modifications, and then convert it back to a string.

s = 'abcdefgh'l = list(s)l[3] = 'r's2 = ''.join(l)

EDIT: As posted in bstpierre's answer, bytearray is probably even better for this task than list, as long as you're not working with Unicode strings.

s = 'abcdefgh'b = bytearray(s)b[3] = 'r's2 = str(b)

转载地址:http://tohbi.baihongyu.com/

你可能感兴趣的文章
北京联通华为光猫HG8346R破解改桥接
查看>>
python使用win32*模块模拟人工操作——城通网盘下载器(一)
查看>>
python append 与浅拷贝
查看>>
Matlab与CUDA C的混合编程配置出现的问题及解决方案
查看>>
2017阿里内推笔试题--算法工程师(运筹优化)
查看>>
python自动化工具之pywinauto(零)
查看>>
python一句话之利用文件对话框获取文件路径
查看>>
PaperDownloader——文献命名6起来
查看>>
PaperDownloader 1.5.1——更加人性化的文献下载命名解决方案
查看>>
如何将PaperDownloader下载的文献存放到任意位置
查看>>
C/C++中关于动态生成一维数组和二维数组的学习
查看>>
系统架构:Web应用架构的新趋势---前端和后端分离的一点想法
查看>>
JVM最简生存指南
查看>>
漂亮的代码,糟糕的行为——解决Java运行时的内存问题
查看>>
Java的对象驻留
查看>>
自己动手写GC
查看>>
Java 8新特性终极指南
查看>>
logback高级特性使用(二) 自定义Pattern模板
查看>>
JVM并发机制探讨—内存模型、内存可见性和指令重排序
查看>>
可扩展、高可用服务网络设计方案
查看>>