美图齐众专注资阳网站设计 资阳网站制作 资阳网站建设
资阳网站建设公司服务热线:028-86922220

网站建设知识

十年网站开发经验 + 多家企业客户 + 靠谱的建站团队

量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决

Python 程序:用字符串中的连字符替换空格

创新互联python教程:

海港ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为成都创新互联公司的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:18982081108(备注:SSL证书合作)期待与您的合作!

写一个 Python 程序,用替换函数用字符串中的连字符替换空格,用一个实际例子替换 For 循环。

用连字符替换字符串中空格的 Python 程序示例 1

这个 python 程序允许用户输入一个字符串。接下来,我们使用内置的替换字符串函数用连字符替换空白。

# Python program to Replace Blank Space with Hyphen in a String

str1 = input("Please Enter your Own String : ")

str2 = str1.replace(' ', '_')

print("Original String :  ", str1)
print("Modified String :  ", str2)

Python 用连字符输出替换字符串中的空格

Please Enter your Own String : Hello World Program
Original String :   Hello World Program
Modified String :   Hello_World_Program

用连字符替换字符串中空格的 Python 程序示例 2

在这个程序中,我们使用 For 循环来迭代字符串中的每个字符。在 For 循环中,我们使用 If 语句来检查字符串字符是空的还是空格。如果是真的, Python 会用 _。

# Python program to Replace Blank Space with Hyphen in a String

str1 = input("Please Enter your Own String : ")

str2 = ''

for i in range(len(str1)):
    if(str1[i] == ' '):
        str2 = str2 + '_'
    else:
        str2 = str2 + str1[i]

print("Modified String :  ", str2)

Python 用连字符输出替换字符串中的空格

Please Enter your Own String : Hello World!
Modified String :   Hello_World!
>>> 
Please Enter your Own String : Python program Output
Modified String :   Python_program_Output

用连字符替换字符串中空格的 Python 程序示例 3

这个 Python 用连字符替换空格的程序与上面的例子相同。然而,我们使用的是对象循环。

# Python program to Replace Blank Space with Hyphen in a String

str1 = input("Please Enter your Own String : ")

str2 = ''

for i in str1:
    if(i == ' '):
        str2 = str2 + '_'
    else:
        str2 = str2 + i

print("Modified String :  ", str2)


新闻标题:Python 程序:用字符串中的连字符替换空格
文章分享:http://zsjierui.cn/article/dhohdse.html

其他资讯