首页 > 编程知识 正文

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

时间:2023-11-24 15:33:40 阅读:308882 作者:OXOA

写一个 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)

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。