python中如何让字符串中某几个字符成为变量?比如循环输出test1 test2 test3
时间: 2023-09-10 15:07:14 浏览: 43
可以使用字符串格式化来实现:
```
for i in range(1, 4):
print("test{}".format(i))
```
输出结果为:
```
test1
test2
test3
```
在字符串中使用 `{}` 来表示要插入变量的位置,然后使用 `format()` 方法来将变量插入字符串中。在本例中,使用 `range(1, 4)` 生成 1 到 3 的整数序列,然后在循环中用这些数字替换 `{}` 中的空位,生成字符串 `"test1"`、`"test2"` 和 `"test3"`。
相关问题
python实现从键盘输入一个字符串,将小写字母全部转换为大写字母,然后输出到一个磁盘文件test.txt中保存
好的,您的问题是如何用Python将键盘输入的字符串中的小写字母转为大写字母,并保存到磁盘文件test.txt中。下面是Python代码实现:
```python
# 从键盘输入一个字符串
input_str = input("请输入一个字符串:")
# 将字符串中的小写字母转为大写字母
upper_str = input_str.upper()
# 将字符串保存到磁盘文件中
with open('test.txt', 'w') as f:
f.write(upper_str)
print("转换成功,并已将结果保存到文件test.txt中。")
```
这段代码中,首先使用`input()`函数从键盘获取一个字符串,然后使用字符串的`upper()`方法将所有小写字母转为大写字母,保存到变量`upper_str`中。最后使用`open()`函数打开文件`test.txt`,使用`write()`方法写入转换后的字符串,并在`with`语句中自动关闭文件。最后输出转换成功的信息。
在本地建立test.txt,依次输出倒数第2、3、4个字符。
可以使用Python来实现这个任务。具体的代码如下所示:
```python
with open('test.txt', 'r') as f:
content = f.read()
print(content[-2])
print(content[-3])
print(content[-4])
```
首先使用`with open('test.txt', 'r') as f`打开名为`test.txt`的文件,并将其读取到变量`content`中。然后使用负数索引来输出倒数第2、3、4个字符。注意,负数索引表示从字符串末尾开始计数,因此`content[-2]`表示倒数第2个字符,`content[-3]`表示倒数第3个字符,以此类推。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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_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)
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)