独书先生 Menu

Python初学者笔记(3):输出列表中的奇数/奇数项,字符串中的偶数项,字符串大小写转换

【1】a=[8,13,11,6,26,19,24]
1)请输出列表a中的奇数项
2)请输出列表a中的奇数

解:1)

a=[8,13,11,6,26,19,24] 
print a[::2]

Result:
>>>
[8, 11, 26, 24]

2)

a = [8,13,11,6,26,19,24]
b = []
for item in a:
    if item%2 !=0:
        b.append(item)
    else:
        continue
print b

Result:
>>>
[13, 11, 19]


【2】st = ‘Hello Python DuShuSir’请输出st字符串中偶数位上的字符

解:方法一:

st = 'Hello Python DuShuSir'
sr =''
i=0
while i<len(st):
    if i%2!=0:
        sr +=st[i]
    i +=1
print sr

方法二:

st = 'Hello Python DuShuSir'
print st[1::2]

Result:
>>>
el yhnDSui


【3】已知字符串 a = “dUsHUsIR6cOM6”,要求 :
1)请将a字符串改为小写或改为大写
2)将a字符串中的小写改为大写、大写改为小写

解:1)

a = "dUsHUsIR6cOM6"
print a.upper()  
print a.lower()

Result:
>>>
DUSHUSIR6COM6
dushusir6com6

2)

a = "dUsHUsIR6cOM6"
b = ""
i=0
while i<len(a):
    if a[i].isupper():
        b +=a[i].lower()
    elif a[i].islower():
        b +=a[i].upper()
    elif a[i].isdigit():
        b +=a[i]
    i +=1
print b

Result:
>>>
DuShuSir6Com6