Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/308.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.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_Return_Add_Updates - Fatal编程技术网

Python 仅拆分字符串更新编号

Python 仅拆分字符串更新编号,python,string,return,add,updates,Python,String,Return,Add,Updates,我有一个函数,使用原始输入从用户那里获取一个句子。然后,我的第二个函数拆分句子,所以我只想更新句子上的数字。这是一个分裂的句子: ['You', 'are', '42', 'this', 'year'] 我正在尝试更新42到43,做一个返回并打印“你今年43岁” 我可以使用isdigit()提取数字,但不能增加它。这就是我到目前为止所做的: def GetDigits(sentence): for i in sentence: if i.isindigit():

我有一个函数,使用原始输入从用户那里获取一个句子。然后,我的第二个函数拆分句子,所以我只想更新句子上的数字。这是一个分裂的句子:

['You', 'are', '42', 'this',  'year']
我正在尝试更新42到43,做一个返回并打印“你今年43岁”

我可以使用isdigit()提取数字,但不能增加它。这就是我到目前为止所做的:

def GetDigits(sentence):
    for i in sentence:
        if i.isindigit():
           i = i +1
    return sentence

您正在尝试向字符串添加1,因为
'42'
42
不同

您需要先使用
int(v)
'42'
更改为
int
,然后增加它

def GetDigits(sentence):
    for i, v in enumerate(sentence):
        if v.isdigit():
           sentence[i] = str(int(v) + 1)
    return sentence

有一种用于字符串的内置方法更适合于此,
format()

如果需要更新,您可以:

print(sentence.format(int(age) + 1))
或者,作为使用生成器的函数:

def get_digits(sentence):
    return ' '.join(str(int(word) + 1) if word.isdigit() else word for word in sentence.split())

Python中的数字是不可变的对象,因此当您执行
i=i+1
时,您正在创建一个新对象。此新对象不是原始
语句的一部分。另外,“42”是一个字符串。无法对其应用数字添加操作。您需要先将其转换为整数

这就是你需要的-

def GetDigits(sentence):
    for idx, value in enumerate(sentence):
        if value.isdigit():
           sentence[idx] = int(value) +1
    return sentence

这里的关键问题是,您试图找到一个函数,该函数可以让您知道何时将字符串转换为int是安全/正确的,但是没有这样的函数。有各种近似方法,但最简单的方法是尝试转换字符串。这是Python中的一般原则。该语言的设计是基于这样一个事实,即检查某件事情是否有效的方法是只做它,然后处理它不起作用的情况(通常意味着异常)。试图对抗这种设计只会让你的生活更艰难

但这不是唯一的问题;这里有很多问题

  • isindigit
    不是字符串的方法。也许你是说
    isdigit

  • isdigit
    不能为您提供正确答案,比如说,
    -3
    -或者,就这一点而言,非西方脚本中的整数(对于
    isdigit
    可能返回true,但实际上Python不能将其解释为整数)

  • 仅仅因为
    i
    是表示整数的字符串并不意味着它是整数;它仍然是一个字符串,
    i+1
    仍然是一个
    TypeError
    。您需要调用
    int(i)
    以获取其作为数字的值

  • 仅仅重新分配给
    i
    根本不会影响
    句子。您所做的只是将局部变量
    i
    转换为不同值的名称。您需要对该
    i
    执行一些操作-要么构建一个新句子,要么在适当的位置修改句子(例如,通过使用
    enumerate
    跟踪索引,这样您就可以执行
    句子[索引]=…

  • 虽然还不清楚您对结果做了什么,但我敢打赌,您确实希望返回字符串,而不是字符串和整数的混合,因此在添加1后,您可能希望转换回
    str

所以,你想要的是这样的:

def GetDigits(sentence):
    new_sentence = []
    for i in sentence:
        try:
            i = str(int(i) + 1)
        except ValueError:
            pass
        new_sentence.append(i)
    return new_sentence

然而,这可能有点太聪明了。如果
i
不表示整数,
int(i)
将引发
ValueError
,这意味着
i
仍然引用原始字符串,我们将其添加到
新句子中。否则,我们将把它转换成一个整数,加上1,再转换回一个字符串,并使
i
引用这个新字符串,我们将它添加到
new\u-statement
。如果你不明白为什么新句子。附加(i)
总是做正确的事情,你应该更明确地重写它。

另一种通过正则表达式使用
re
模块的黑客方法

import re
sentence = input("Enter the sentence : \n")
def GetDigits(sentence):
    L = []
    for i in sentence.split():
        if re.match(r'\d+$', i):
            i = int(i)+1
            L.append(str(i))
        else:
            L.append(i)
    sentence = ' '.join(L)
    return(sentence)
print(GetDigits(sentence))
输出:

Enter the sentence : 
You are 42 this year
You are 43 this year

使用正则表达式在这里添加了什么?为什么使用
$
而不是
^
?您是否试图使它与
-23
匹配?如果是这样,您需要
search
而不是
match
——然后您还需要处理
a23
也匹配,但会引发异常的事实。酷。你应该接受其中一个答案。
Enter the sentence : 
You are 42 this year
You are 43 this year