簡體   English   中英

如何將字符串中的數字轉換為下划線 output

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

我正在努力完成一項家庭作業,但我有點迷茫。 我需要使用 python 編寫一個程序,我需要輸入一個字符串,然后輸入 output 字符串。 很簡單,但我的任務要求如果字符串有任何數字,output 將打印下划線而不是數字“_”。

  • 例子。

輸入一個字符串:你好,我今年 7 歲。

(必填 Output:你好,我 _ 歲。)

到目前為止,這是我當前的代碼。

string =input("Input a string? ")

print("Output:",string)

你能幫我理解這是如何實現的嗎,因為我對 python 還很陌生。

您可以使用 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