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

编写一个Python程序,使用replace函数和for循环,并提供实际示例,将字符串中的空格替换为连字符。

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

这个Python程序允许用户输入一个字符串。然后,我们使用内置的replace字符串函数将空格替换为连字符。

# 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替换空格为连字符的程序与上面的示例相同。但是,我们使用的是带对象的for循环。

# 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 program to Replace Blank Space with Hyphen in a String