1 #coding:utf-8
2 #字符串的操作
3 #使用中括号[]可以从字符串中取出任一个连续的字符
4 #注意:中括号内表达式是字符串的索引,它表示字符在字符串内的位置,
5 #中括号内字符串第一个字符的索引是0,而不是1
6 #len返回字符串的长度
7  
8 test_string = "1234567890"
9  print test_string[0] #result = 1
10  print test_string[1] #result = 2
11  print test_string[9] #result = 0
12 print len(test_string) #result = 10
13
14 #使用for循环遍历字符串
15 for i in test_string:
16 print i
17 if (i == '5'):
18 print "Aha,I find it!"
19 print type(i) #<type 'str'>
20
21 #提取字符串的一部分
22 #操作符[n:m]返回字符串中的一部分。从第n个字符串开始,到第m个字符串结束。
23 #包括第n个,但不包括第m个。
24 #如果你忽略了n,则返回的字符串从索引0开始
25 #如果你忽略了m,则字符串从n开始,到最后一个字符串
26
27 test_string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
28 print test_string[0:5] #result = 'ABCDE'
29 print test_string[8:11] #result = 'IJK'
30 print test_string[:6] #result = 'ABCDEF'
31 print test_string[20:] #result = 'UVWXYZ'
32 print test_string[:] #result = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

 

 

 

相关文章:

  • 2021-09-22
  • 2018-10-21
  • 2021-10-10
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-09
  • 2022-01-25
猜你喜欢
  • 2022-01-18
  • 2021-11-27
  • 2019-02-26
  • 2022-12-23
  • 2021-09-17
  • 2021-11-17
  • 2021-09-13
相关资源
相似解决方案