coding:去除字符串的空格
时间: 2024-04-08 11:34:57 浏览: 6
可以使用 Python 中的 `replace()` 方法或者正则表达式来去除字符串的空格。
使用 `replace()` 方法的示例代码如下:
```python
string = " Hello, World! "
new_string = string.replace(" ", "")
print(new_string) # 输出:Hello,World!
```
使用正则表达式的示例代码如下:
```python
import re
string = " Hello, World! "
new_string = re.sub(r"\s+", "", string)
print(new_string) # 输出:Hello,World!
```
这两种方法都会将字符串中的所有空格替换为空字符串,从而去除空格。
相关问题
去掉字符串数组中每个字符串的空格
要去掉字符串数组中每个字符串的空格,可以使用列表推导式和字符串的`replace()`方法来实现。以下是一个示例代码:
```python
def remove_spaces(strings):
return [s.replace(" ", "") for s in strings]
# 测试
strings = ["Hello World", "Python is awesome", " I love coding "]
new_strings = remove_spaces(strings)
print(new_strings)
# 输出:['HelloWorld', 'Pythonisawesome', 'Ilovecoding']
```
在上述代码中,我们定义了一个`remove_spaces()`函数,它接受一个字符串数组作为输入。使用列表推导式,遍历数组中的每个字符串,并使用`replace()`方法将空格替换为空字符串。最后,返回一个新的字符串数组。
通过调用`remove_spaces()`函数,我们可以得到去掉空格后的新字符串数组`new_strings`。输出结果就是去掉了空格的字符串数组。
用python实现去掉字符串数组中每个字符串的空格
可以使用以下代码来实现去掉字符串数组中每个字符串的空格:
```python
def remove_spaces(strings):
new_strings = []
for string in strings:
new_string = string.replace(" ", "")
new_strings.append(new_string)
return new_strings
# 示例用法
strings = ["hello world", " python ", " coding "]
new_strings = remove_spaces(strings)
print(new_strings)
```
在上述代码中,我们定义了一个名为 `remove_spaces` 的函数,它接受一个字符串数组作为参数。在函数内部,我们创建了一个新的空数组 `new_strings`,用于存储去掉空格后的每个字符串。然后,我们使用 `replace()` 方法将每个字符串中的空格替换为空字符,并将替换后的字符串添加到新数组 `new_strings` 中。最后,我们返回新数组。
在示例用法部分,我们定义了一个字符串数组 `strings`,其中包含了一些带有空格的字符串。然后,我们调用 `remove_spaces` 函数,并将返回的新数组存储在 `new_strings` 变量中。最后,我们输出 `new_strings` 的内容,即去掉空格后的字符串数组。
请注意,上述代码中使用了 `replace()` 方法来去掉空格。如果你想只去掉字符串开头和结尾的空格,可以使用 `strip()` 方法。