for循环;range,len函数;in操作符

本文介绍了Python中for循环的基本用法,包括遍历字符串、使用range函数进行计数,以及倒序计数等。同时,文章还展示了如何利用len()函数获取字符串长度,使用in运算符检查字符串中是否包含特定字符,以及通过随机索引访问字符串中的字符。

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

#for循环
word = input("Enter a word:")
print("\nHere's each letter in your word:")
for letter in word:
    print(letter)
    
Enter a word:lzq

Here's each letter in your word:
l
z
q
#range函数
print("Counting:")
for i in range(10):
    print(i,end=" ")
    
print("\n\nCounting by five:")
for i in range(0,50,5):
    print(i,end=" ")
    
print("\n\nCounting backwards:")
for i in range(10,0,-1):
    print(i,end=" ")
    
Counting:
0 1 2 3 4 5 6 7 8 9 

Counting by five:
0 5 10 15 20 25 30 35 40 45 

Counting backwards:
10 9 8 7 6 5 4 3 2 1 
# len()函数和in运算符
message = input("Enter a message:")

print("\nThe length of your message is:",len(message))

print("\nThe most common letter in the English language'e'")
if "e" in message:
    print("is in your message.")
else:
    print("is not in your message.")
    
Enter a message:lzq like to study.

The length of your message is: 18

The most common letter in the English language'e'
is in your message.
#字符串的索引
import random

word = "index"
print("The word is:%s\n"%word)

high = len(word)
low = -len(word)

for i in range(10):
    position = random.randrange(low,high)  #不包含high
    print("word[%d]:%s"%(position,word[position]))
    
The word is:index

word[2]:d
word[-4]:n
word[3]:e
word[-1]:x
word[3]:e
word[1]:n
word[-1]:x
word[-2]:e
word[-5]:i
word[3]:e

### C++ 中的操作符重载方法 在 C++ 编程语言中,操作符可以通过定义特定形式的函数来实现其功能扩展。这种技术被称为 **操作符重载**。它允许程序员改变某些现有操作符的行为方式以便它们可以用于用户自定义的数据类型。 #### 1. 基本概念 C++ 支持通过 `operator` 关键字定义新的行为模式。例如,要重载某个二元操作符(如加法 `+` 或插入器 `<<`),需要创建一个具有特殊名称的形式化函数——即 `operator@` 函数 [@ 表示实际被重载的操作符] [^2]。 对于标准库中的流对象 `std::cout` 所使用的插入操作符 `< <<>` ,这是一个典型的例子展示如何利用已有的类成员函数完成数据输出的任务 [^1]: ```cpp #include <iostream> using namespace std; int main() { cout << "Hello out there.\n"; // 插入字符串到控制台的标准输出流上 } ``` 上述代码片段展示了最基础的应用场景之一:将文字消息传递给屏幕显示出来的同时也体现了该机制背后的工作原理 —— 调用了 ostream 类型内部预设好的 operator<< 成员版本来进行处理。 #### 2. 实现细节 当涉及到更复杂的结构体或者类时,则可能需要手动编写这些特殊的 member functions 来满足需求。下面是一个简单的示范程序说明怎样去构建属于自己的 string class 并为其提供赋值(`=`)以及索引访问(`[]`)的功能支持: ##### 头文件(String.h) ```cpp #ifndef STRING_H_ #define STRING_H_ class String { private: char* str; public: explicit String(const char* s = ""); ~String(); const String& operator=(const String&); char& operator[](size_t index); }; #endif /*STRING_H_*/ ``` ##### 源文件(String.cpp) ```cpp #include "String.h" #include <cstring> // 构造函数初始化指针指向动态分配内存区域存储传进来的内容副本 String::String(const char *s){ size_t length=strlen(s)+1; this->str=new char[length]; strcpy(this->str,s); } //析构释放资源防止泄露 String::~String(){ delete []this->str; } //重写等于号运算子逻辑 const String& String::operator=(const String &other){ if(&other !=this){ // 自己给自己赋值的情况忽略掉 delete []this->str;//先清理旧有空间再重新配置新大小并复制过去相应字符序列 size_t len=strlen(other.str)+1; this->str= new char[len]; strcpy(this->str, other.str); } return (*this); } //数组下标的存取设定 char& String::operator[](size_t index){ static char nullChar='\0'; if(index >= strlen(str)){ throw std::out_of_range("Index out of range"); }else{ return *(this->str +index ); } } ``` ##### 主测试(Test.cpp) ```cpp #include "String.h" #include <iostream> using namespace std; void testAssignmentAndSubscripting(); int main(){ try{ testAssignmentAndSubscripting(); }catch(exception&e ){ cerr<<"Exception caught:"<<e.what()<<endl; } return EXIT_SUCCESS; } void testAssignmentAndSubscripting(){ String a="Original"; String b=a; //调用拷贝构造而非简单地做浅层copy cout<<"Before modification:\na="<<a<<"\nb="<<b<<'\n'; b[7]='d';//[ ] 运算符修改了原string内容因为它是non-constant reference type. b=b+a+"Suffix"; cout<<"After modifications:\na="<<a<<"\nb="<<b<<'\n'; } ``` 此实例演示了一个基本字符串管理系统的开发过程,其中包含了两个重要的操作符重载部分: - 等于 (`=`): 提供深拷贝能力以避免多个变量共享同一份底层资料的风险; - 方括弧 (`[]`): 允许像常规数组那样随机读/写单个位置上的元素值。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值