Python 为什么我没有得到输入来键入字符串?(我想用下划线替换所有数字)
您似乎误解了Python 为什么我没有得到输入来键入字符串?(我想用下划线替换所有数字),python,string,input,Python,String,Input,您似乎误解了isdigit和replace的工作原理isdigit是一种字符串方法,返回True字符串是数字还是False(如果不是)。注意,您实际上并没有使用isdigit方法,而是将名称用作变量替换将一个子字符串替换为字符串中的另一个子字符串,但不处理抽象子字符串,如“数字字符串”。以下是实现您所想的两种方法: 示例#1: 输出: test_string = "this 1 is a 2 test 3 with4 a num5ber of dig6its in it."
isdigit
和replace
的工作原理isdigit
是一种字符串方法,返回True
字符串是数字还是False
(如果不是)。注意,您实际上并没有使用isdigit
方法,而是将名称用作变量<代码>替换将一个子字符串替换为字符串中的另一个子字符串,但不处理抽象子字符串,如“数字字符串”。以下是实现您所想的两种方法:
示例#1:
输出:
test_string = "this 1 is a 2 test 3 with4 a num5ber of dig6its in it."
converted_string = ""
for char in test_string:
converted_string += "_" if char.isdigit() else char
print(converted_string)
import re
test_string = "this 1 is a 2 test 3 with4 a num5ber of dig6its in it."
converted_string = re.sub("\d", "_", test_string)
print(converted_string)
示例2:
输出:
test_string = "this 1 is a 2 test 3 with4 a num5ber of dig6its in it."
converted_string = ""
for char in test_string:
converted_string += "_" if char.isdigit() else char
print(converted_string)
import re
test_string = "this 1 is a 2 test 3 with4 a num5ber of dig6its in it."
converted_string = re.sub("\d", "_", test_string)
print(converted_string)
这是你真正的密码吗?这似乎是假的…欢迎来到SO!请拿着这本书读一读。你说的“没有得到输入”是什么意思?代码的第一行提示输入。我刚刚运行了它,它运行得很好,尽管程序稍后会出错。请澄清。另外,对于调试帮助,最好提供一个@Word,它是Python,lol:)
this _ is a _ test _ with_ a num_ber of dig_its in it.