我想从字符串中读取一些字符并将其放入其他字符串中(就像我们在C中所做的那样).
所以我的代码如下所示
import string
import re
str = "Hello World"
j = 0
srr = ""
for i in str:
srr[j] = i #'str' object does not support item assignment
j = j + 1
print (srr)
Run Code Online (Sandbox Code Playgroud)
在C中代码可能是
i = j = 0;
while(str[i] != '\0')
{
srr[j++] = str [i++];
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能在Python中实现相同的功能?
这个简单的代码只是试图用冒号替换分号(在i指定的位置)不起作用:
for i in range(0,len(line)):
if (line[i]==";" and i in rightindexarray):
line[i]=":"
Run Code Online (Sandbox Code Playgroud)
它给出了错误
line[i]=":"
TypeError: 'str' object does not support item assignment
Run Code Online (Sandbox Code Playgroud)
我如何解决这个问题用冒号代替分号?使用replace不起作用,因为该函数不带索引 - 可能有一些我不想替换的分号.
例
在字符串中我可能有任意数量的分号,例如"Hei der !; Hello there;!;"
我知道我想要替换哪些(我在字符串中有他们的索引).使用replace不起作用,因为我无法使用索引.
我需要在内存中短时间存储用户密码.我怎么能这样做却没有在coredumps或追溯中意外披露这些信息?有没有办法将值标记为"敏感",因此它不会被调试器保存在任何地方?
如何从特定索引替换字符串中的字符?例如,我想从字符串中获取中间字符,如abc,如果字符不等于用户指定的字符,那么我想替换它.
这样的事可能吗?
middle = ? # (I don't know how to get the middle of a string)
if str[middle] != char:
str[middle].replace('')
Run Code Online (Sandbox Code Playgroud) 如何在Python中修改字符串中的单个字符?就像是:
a = "hello"
a[2] = "m"
Run Code Online (Sandbox Code Playgroud)
'str'对象不支持项目分配.
只是好奇为什么python会允许我更新列表但不是字符串?
>>> s = "abc"
>>> s[1:2]
'b'
>>> s[1:3]
'bc'
>>> s[1:3] = "aa"
>>> l = [1,2,3]
>>> l[1:3]
[2, 3]
>>> l[1:3] = [9,0]
>>> l
[1, 9, 0]
Run Code Online (Sandbox Code Playgroud)
有这么好的理由吗?(我确信有.)
我是 Python 新手,从昨天开始,我遇到了一个问题。我试图将它减少到几行,基本上,字符串没有更新。
e = '*****'
for i in e:
if e.index(i) == 2:
e = e.replace(i, 'P')
print(e)
# *****
Run Code Online (Sandbox Code Playgroud) 我正在尝试使用一些 for 循环来取一个句子并将每个单词的第一个字母大写。
p1 = "the cat in the hat"
def title_creator(p1):
p = p1.split()
p_len = len(p)
d = []
for i in range(p_len):
first_letter = p[i][0]
m = first_letter.upper()
d.append(m)
p[i][0] == d[i]
p = " ".join(p)
return p
z = title_creator(p1)
print(z)
Run Code Online (Sandbox Code Playgroud)
这从顶部输出相同的原始句子。我如何能够将索引从一个列表替换为另一个列表?
-ps 如果这个问题真的很简单,我很抱歉,我只是忽略了一些简单的事情。