Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/tfs/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
更改字符串中的python索引_Python_String_Indexing - Fatal编程技术网

更改字符串中的python索引

更改字符串中的python索引,python,string,indexing,Python,String,Indexing,我有以下问题: 让我们假设s='ab'。len(s)=2。它有两个索引:0和1。我想做的是使ab的长度为1,或者索引为0 欢迎一切帮助 谢谢如果我理解了你的问题,那么我猜你在寻找切片: >>> s = 'ab' >>> s = s[:1] >>> s 'a' 更新: 你需要一份清单来做这件事 >>> d ='abcefg' >>> it = iter(d) >>> d = [x + ne

我有以下问题:

让我们假设s='ab'。len(s)=2。它有两个索引:0和1。我想做的是使ab的长度为1,或者索引为0

欢迎一切帮助


谢谢

如果我理解了你的问题,那么我猜你在寻找切片:

>>> s = 'ab'
>>> s = s[:1]
>>> s
'a'
更新:

你需要一份清单来做这件事

>>> d ='abcefg'
>>> it = iter(d)
>>> d = [x + next(it) for x in it] #creates a list
>>> d
['ab', 'ce', 'fg']
>>> d[0]
'ab'
>>> d[1]
'ce'
>>> d[2]
'fg'
另一种使用
zip
的方法:

>>> d ='abcefg'
>>> it = iter(d)
>>> [x+y for x,y in zip(it,it)]
['ab', 'ce', 'fg']

我认为你的问题有两种答案:

>>> s = 'ab'
>>> s = s[:1]
>>> s
'a'
或者您希望字符串存储在集合中

>>> s = 'ab'
>>> s = (s,)
>>> s[0]
'ab'

>>> s = 'ab'
>>> s = [s]
>>> s[0]
'ab'

不安静,例如d='abcefg'。我想要的是d[0]='ab',d[1]='ce',d[2]=[fg]。@IsaacAltair在你的问题中添加这样的例子,我已经更新了我的解决方案。我们不允许在作业中使用列表,但了解各种解决方案非常好。谢谢D@IsaacAltair你不能用字符串来做这件事,在字符串中索引只指向一个字符。@IsaacAltair什么是
打印板
?这与你原来的问题无关。