coding:去除字符串的空格
时间: 2024-04-08 18:34:57 浏览: 26
你可以使用编程语言中的字符串处理函数或方法来去除字符串中的空格。下面是一些常见编程语言的示例:
在Python中,你可以使用`replace`方法或`join`函数来去除字符串中的空格。例如:
```python
string_with_spaces = "Hello, World!"
string_without_spaces = string_with_spaces.replace(" ", "") # 使用replace方法
print(string_without_spaces) # 输出: "Hello,World!"
# 或者使用join函数
string_without_spaces = ''.join(string_with_spaces.split())
print(string_without_spaces) # 输出: "Hello,World!"
```
在Java中,你可以使用`replaceAll`方法来去除字符串中的空格。例如:
```java
String stringWithSpaces = "Hello, World!";
String stringWithoutSpaces = stringWithSpaces.replaceAll("\\s", "");
System.out.println(stringWithoutSpaces); // 输出: "Hello,World!"
```
在JavaScript中,你可以使用`replace`方法或正则表达式来去除字符串中的空格。例如:
```javascript
let stringWithSpaces = "Hello, World!";
let stringWithoutSpaces = stringWithSpaces.replace(/\s/g, "");
console.log(stringWithoutSpaces); // 输出: "Hello,World!"
```
以上是一些常见的示例,具体的实现方式可能会因使用的编程语言而略有不同。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
# -- coding: utf-8 -- import urllib.request import re def getNovertContent(): url = 'http://www.quannovel.com/read/640/' req = urllib.request.Request(url) req.add_header('User-Agent', ' Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36') data = urllib.request.urlopen(req).read().decode('gbk') str1 = str(data) # 将网页数据转换为字符串 reg = r'(.*?)' reg = re.compile(reg) urls = reg.findall(str1) for url in urls: novel_url = url[0] novel_title = url[1] chapt = urllib.request.urlopen(novel_url).read() chapt_html = chapt.decode('gbk') reg = r'</script> (.*?)</script type="text/javascript">' reg = re.compile(reg, re.S) chapt_content = reg.findall(chapt_html) chapt_content = chapt_content[0].replace( " ", "") chapt_content = chapt_content.replace("
", "") print("正在保存 %s" % novel_title) with open("{}.txt".format(novel_title), 'w', encoding='utf-8') as f: f.write(chapt_content) getNovertContent()
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)