python声明字符串变量
时间: 2023-08-27 11:08:20 浏览: 95
在Python中,可以使用单引号或双引号来声明字符串变量。例如:
```
str1 = 'Hello World'
str2 = "I love Python"
```
你还可以使用三引号来声明多行字符串变量,例如:
```
str3 = '''This is a multi-line
string in Python'''
```
此外,你还可以使用字符串格式化和字符串替换来操作字符串。字符串格式化可以使用`format()`方法,例如:
```
name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
```
字符串替换可以使用`replace()`方法,例如:
```
sentence = "I love Java"
new_sentence = sentence.replace("Java", "Python")
print(new_sentence)
```
还有一些其他的字符串操作方法,比如删除空白字符。你可以使用`strip()`方法来删除字符串两侧的空白字符,或使用`lstrip()`和`rstrip()`方法来删除字符串左侧和右侧的空白字符。例如:
```
p = ' python\t'
print(p.strip())
```
这样会删除字符串两侧的空白字符和制表符。
#### 引用[.reference_title]
- *1* *3* [Python字符串变量基础](https://blog.csdn.net/weixin_51492608/article/details/127359878)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* [python基础之字符串(string类型)](https://blog.csdn.net/qq_34782203/article/details/127321588)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文