Python—变量与字符串

本文介绍了一系列使用Python进行字符串操作的方法,包括字符串的拼接、格式化、替换、切片等实用技巧。通过具体实例展示了如何高效地处理字符串,适用于初学者及日常开发中遇到字符串处理需求的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

打开文件,写入字符串

file = open('/D/file.txt','w')
file.write('hello world!')

字符串组合输出

a = 'plays '
b = 'guitar '
c = 'Mr.Charles.'
d = c + a + b
print(d)

数字转字符类型进行输出

num = 1
string = '1'
num2 = int(string)
print(num + num2)

字符串*数字1:

words = 'words' * 3
print(words)

字符串*数字2:

word = 'a loooooong word'
num  = 12
string  = 'bang!'
total = string * (len(word) - num)
print(total)

字符串用下标进行输出

name = 'My name is Charles'
print(name[0])
'M'
print(name[-4])
'r'
print(name[11:14])
'Cha'
print(name[11:15])
'Char'
print(name[5:])
'me is Chrales'
print(name[:5])
'My na'

字符串下标的组合输出

word = 'friends'
find = word[0] + word[2:4] + word[-3:-1]
print(find)

爬取文件命名(字符串下标)

url = 'http://ww1.site.cn/14d2e8ejw1exjogbxdxhj20ci0kuwex.jpg'
file_name = url[-10:]

print(file_name)

字符串replace函数,用*代替对应位置字符

number = '1777-917-7829'
hnumber = number.replace(number[:9],'*'* 9 )
print(hnumber)

查找字符串中的子串

search = '168'
num_a = '1398-168-0006'
num_b = '1681-222-0006'
print(search + ' is at ' + str(num_a.find(search)) + ' to ' + str(num_a.find(search) + len(search) - 1) + ' of num_a')

字符串format函数用法(填空)

print('{} name is {}.'.format('My','Charles'))

 

### 创建和使用带变量字符串Python 中有多种方式可以创建并使用带有变量字符串。以下是几种常用的方法: #### 使用 f-string (格式化字符串字面量) 自 Python 3.6 起支持的一种简洁而直观的方式来嵌入表达式的值到字符串中。只需在字符串前加 `f` 或者 `F`,接着就可以直接把变量名放在花括号 `{}` 内部。 ```python name = "Alice" age = 25 message = f"My name is {name}, and I am {age} years old." print(message) ``` 这种方法不仅易于阅读而且执行效率高[^3]。 #### 利用 `.format()` 方法 对于较早版本的 Python(低于 3.6),或者当希望保持兼容性时,`.format()` 函数是一个不错的选择。它允许通过位置参数或关键字参数的形式向模板化的字符串传递数据。 ```python greeting = "{} comes from {}." formatted_greeting = greeting.format("Bob", "China") print(formatted_greeting) ``` 也可以指定命名参数以便更清晰地映射输入值: ```python template = "{person}'s favorite color is {color}." filled_template = template.format(person="Charlie", color="blue") print(filled_template) ``` 这种方式提供了灵活性,特别是在处理复杂格式的情况下[^2]。 #### 将字典转换成 JSON 字符串 如果目标是在 JSON 格式的字符串里插入动态内容,则可以通过先构建一个包含所需键值对的字典对象,再利用内置库 `json` 来完成这一操作。 ```python import json data_dict = {"key": "value"} json_string = json.dumps(data_dict) print(json_string) ``` 此过程会自动转义特殊字符以确保生成合法的 JSON 文本[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值