Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/356.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 - Fatal编程技术网

在python字符串中的特定范围内迭代

在python字符串中的特定范围内迭代,python,Python,我很难弄清楚如何在python中迭代字符串。我的目标是迭代到字符串中的某个点,并删除该迭代点之后的其余元素,只处理子字符串 假设我有一个字符串,比如str1:str1=“8493 2020” 我有一个数字指定我要迭代的距离,比如说a=4 如何在str1上迭代到-然后删除a之后的所有字符 我尝试了这一点,但出现了“TypeError:“str”对象不可调用”的语法错误: 您可以迭代一个切片 >>> str1 = "8493 2020" >>> a = 4 >

我很难弄清楚如何在python中迭代字符串。我的目标是迭代到字符串中的某个点,并删除该迭代点之后的其余元素,只处理子字符串

假设我有一个字符串,比如str1:
str1=“8493 2020”
我有一个数字指定我要迭代的距离,比如说
a=4

如何在str1上迭代到-然后删除a之后的所有字符

我尝试了这一点,但出现了“TypeError:“str”对象不可调用”的语法错误:


您可以迭代一个切片

>>> str1 = "8493 2020"
>>> a = 4
>>> for i in str1[:a]:
        print i


8
4
9
3
如果您需要创建一个新字符串,只需这样做

>>> b = str1[:a]
>>> b
'8493'

这将生成一个新字符串x,而不包含字符串中不需要的部分。字符串是不可变的,因此需要创建一个新字符串

迭代到所需索引:

>>> str1 = "8493 2020"
>>> a = 4
>>> for i in str1[:a]:
...     print i
...
8
4
9
3
删除该索引之前的所有内容:

>>> str1 = str1[:a]
>>> str1
'8493'

这与@Sukritkalla的答案几乎相同。
for i in str1:
   if i == a:
       x = str1[a+1:]
>>> str1 = "8493 2020"
>>> a = 4
>>> for i in str1[:a]:
...     print i
...
8
4
9
3
>>> str1 = str1[:a]
>>> str1
'8493'