Python 字符串——巧取值和列表——巧取值 对比
1.字符串取值实例:
samp_string = "Whatever you are, be a good one." for i in samp_string: print(i) for i in range(0,len(samp_string)-2,2): print(samp_string[i]+samp_string[i+1]) print(‘A=‘,ord("A")) print(‘65=‘,chr(65)) print(‘桃:‘,ord("桃")) print(‘26690‘,chr(26690)) # # You can get a character by referencing an index # print(samp_string[0]) print(samp_string[0]) # # Get the last character print(samp_string[-2]) # # # Get the string length print("Length : ", len(samp_string)) # # # Get a slice by saying where to start and end # # The 4th index isn‘t returned print(samp_string[0:4]) # # # Get everything starting at an index print(samp_string[8:]) # print() # print(samp_string) print(samp_string[::]) print(samp_string[::2]) # # # Reverse the string print(samp_string[::-1]) # # Palindrome print(‘I did, did I?‘[::-1]) print(‘No lemon, no melon‘[::-1]) # # # Practical use url = "http://pythonabc.org" # Get the top level domain print(url[-3:]) # Print the url without the http:// print(url[7:]) # Print the url without the http:// or the top level domain print(url[7:-4])
2,列表取值取值实例
my_list=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 # -10,-9,-8,-7,-6,-5,-4,-3,-2,-1 # 取其中一个值 print(my_list[0]) print(my_list[-10]) print(my_list[-1]) # 取其中几个值 print(my_list[0:5]) print(my_list[-10:-5]) print(my_list[-10:-5:2]) # 逆序输出 print(my_list[::-1]) print(my_list[-1:-10:-1]) # 注意逆序输出,开始点在结束点的后面 print(my_list[-1:-10:-2]) # 注意逆序输出,开始点在结束点的后面 strList=["string",520,21.0] # 列表基本操作 print("列表长度:",len(strList)) print("列表输出",strList) print("两个列表相加为一个列表:",my_list+strList) # 判断一个元素是否为列表中的元素 print("string" in strList) # ************列表相关方法*************************8 # 找出特定元素的索引,字符串使用find方法找到,列表用index方法找到 print(strList.index(520)) for element in strList: print("{}:{}".format(strList.index(element),element)) # 特定元素的的个数 字符串和数组都是使用count方法计算特定子字符串和元素的个数 print("string 的个数:",strList.count(‘string‘)) # 添加元素 strList.append("final") print("string 的更新后个数:",len(strList))
原文地址:https://www.cnblogs.com/lyxcode/p/10914336.html
时间: 2024-10-07 18:00:06