如何用Python接收一个字符串并将每个空白处替换成连字符

119 阅读3分钟

用Python程序接收一个字符串并将每个空白处替换为连字符

Python中的字符串。

字符串是任何计算机语言中最常见的数据类型之一。字符串是一个字符的集合,可以用来表示用户名、博客文章、推特或你代码中的任何其他文本内容。你可以制作一个字符串,并通过这样的方式将其分配给一个变量。

given_string='btechgeeks'

在Python中,字符串被认为是不可改变的,一旦创建,它们就不能被修改。然而,你可以使用各种方法从现有的字符串构造新的字符串。这种形式的编程努力被称为字符串操作。

例子:

Example1:

输入:

given string = hello this is BtechGeeks

输出:

The original string before modification = hello this is BtechGeeks
The new string after modification = hello-this-is-BtechGeeks

例2:

输入:

given string = files will be upload to a folder you can read those files in the program folder

输出:

Enter some random string = files will be upload to a folder you can read those files in the program folder
The original string before modification = files will be upload to a folder you can read those files in the program folder
The new string after modification = files-will-be-upload-to-a-folder-you-can-read-those-files-in-the-program-folder

输入一个字符串并用连字符替换每个空白处的程序

以下是在Python中扫描字符串并用连字符替换每个空白处的方法。

  • 使用替换函数 (静态输入)
  • 使用替换函数(用户输入)

方法#1:使用替换函数(静态输入)

方法:

  • 将字符串作为静态输入并存储在一个变量中。
  • 使用替换函数用连字符替换所有空白,在替换函数中提供空白作为第一个参数,连字符作为第二个参数。
  • 打印修改后的字符串。
  • 程序的退出。

下面是实现的过程

# Give the string as static input and store it in a variable.
given_string = 'hello this is BtechGeeks'
# printing the original string before modification
print('The original string before modification =', given_string)
# Using the replace function replace all blank space with a hyphen by providing blank space as the first argument
# and hyphen as the second argument in replace function.
modified_string = given_string.replace(' ', '-')
# printing the new string after modification
print('The new string after modification =', modified_string)

输出:

The original string before modification = hello this is BtechGeeks
The new string after modification = hello-this-is-BtechGeeks

方法#2:使用替换函数(用户输入)

方法

  • 使用int(input())函数将字符串作为用户输入,并将其存储在一个变量中。
  • 使用替换函数将所有空白处替换为连字符,在替换函数中提供空白处作为第一个参数,连字符作为第二个参数。
  • 打印修改后的字符串。
  • 程序的退出。

下面是实现的过程。

# Give the string as user input using int(input()) function and store it in a variable.
given_string = input('Enter some random string = ')
# printing the original string before modification
print('The original string before modification =', given_string)
# Using the replace function replace all blank space with a hyphen by providing blank space as the first argument
# and hyphen as the second argument in replace function.
modified_string = given_string.replace(' ', '-')
# printing the new string after modification
print('The new string after modification =', modified_string)

输出:

Enter some random string = files will be upload to a folder you can read those files in the program folder
The original string before modification = files will be upload to a folder you can read those files in the program folder
The new string after modification = files-will-be-upload-to-a-folder-you-can-read-those-files-in-the-program-folder

replace()函数用'-'替换了所有""的实例。