我想用"-"替换所有空格



我想用"-"代替所有的空格。

这是我的代码:

print("enter movie name with dashes in spaces,all under case")
print("like this for example")
print("django-unchained")
b=0
a=input("enter movie name now : ")
y=input("Release year? : ")
for x in range (0,len(a)):
if a[b].isspace():
a[b]="-"
b+=1 

上面写着:

TypeError: 'str' object does not support item assignment

在Python中,字符串是不可变的。换句话说,Python不允许您直接将字符串视为字符数组。当您使用a[b]时,您是在特定索引处检索字符,而不是对数组中的元素进行寻址。这里有几个选项:

使用替换

new_string = a.replace(' ', '-')

这是获得你所描述的结果的最简单的方法。如果这是一个简化的示例,并且您出于特殊原因想要索引数组,请尝试下一个选项。

转换为列表

new_list = list(a)

您现在可以修改列表中的单个字符,类似于您最初的方法。

在Python中,字符串是不可变的,这意味着它们不能被改变。

您可以使用replace()代替:

a = a.replace(' ', '-')

你可以这样做:

a=input("enter movie name now : ").replace(" ", "-")
y= input("Release year? : ").replace(" ", "-")
print(a)
print(y)

最新更新