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://gydahua.com/article/dhohdse.html
扫二维码与项目经理沟通

我们在微信上24小时期待你的声音

解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流