简体   繁体   English

如何将字符串中的数字转换为下划线 output

[英]How to convert numbers in a string to underline as output

I am trying to complete a homework task and I am a little bit lost with it.我正在努力完成一项家庭作业,但我有点迷茫。 I need to write a program using python where I need to enter a string and then output the string.我需要使用 python 编写一个程序,我需要输入一个字符串,然后输入 output 字符串。 Simple enough, but my task requires if the string has any numbers, the output will print underline instead of the number " _ ".很简单,但我的任务要求如果字符串有任何数字,output 将打印下划线而不是数字“_”。

  • Example.例子。

input a string: hello I am 7 years old.输入一个字符串:你好,我今年 7 岁。

(REQUIRED Output: hello I am _ years old.) (必填 Output:你好,我 _ 岁。)

So far this Is the current code i have.到目前为止,这是我当前的代码。

string =input("Input a string? ")

print("Output:",string)

Could you please help me understand how this is achieved as I am fairly new to python.你能帮我理解这是如何实现的吗,因为我对 python 还很陌生。

You can use Regex to trade out the numbers for anything.您可以使用 Regex 将数字换成任何东西。

#first I import the module
import re

#then I ask for a string
inputstring = input("Input a string? ")

#here I am taking the string and using regex. the \d does all numbers 0-9 and replaces them with the next argument which is an underscore,finally the input string is placed as the last argument.

finalstring = re.sub('\d', '_', inputstring)

#printing the final edited string
print(finalstring)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM