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 程序:用字符串中的连字符替换空格
标题URL:http://www.hantingmc.com/qtweb/news13/34013.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联