python入门-字符串

大小写转换

 x=[i.upper() if(i.islower()) else i.lower() for i in s]
 print("".join(x))

或者是

s.swapcase()

Split and Join

Sample Input:
this is a string
Sample Output:
this-is-a-string

def split_and_join(line):
    # write your code here
    return '-'.join(line.split(' '))

输出各种格式

a='aa'
b='bb'
x=0.666

print("Hello %s %s %.1f %d! You just delved into python."%(a,b,x,x)
)

输出:
Hello aa bb 0.7 0 ! You just delved into python.

更改字符串

字符串无法直接修改,可以有以下两种方式:

string = "abracadabra"
l = list(string)
l[5] = 'k'
string = ''.join(l)
print string

输出:
abrackdabra
或者:

string = string[:5] + "k" + string[6:]
print string

判断字符串是否包换字母数字

s = input()
print(any(c.isalnum() for c in s))
print(any(c.isalpha() for c in s))
print(any(c.isdigit() for c in s))
print(any(c.islower() for c in s))
print(any(c.isupper() for c in s))

any():若数据都是0或者False则返回False,否则返回True。

每个单词首字母大写

def capitalize(string):
    for i in string.split(" "):
        string=string.replace(i,i.capitalize())
    return string
capitalize()是对字符串的第一个字母大写,并非每个单词

将数字转换成十,八,十六,二进制

def fun(N):
    width = len(bin(N)) - 2
    for i in range(1,N+1):
        print ("{0:{width}d} {0:{width}o} {0:{width}X} {0:{width}b}".format(i,width = width))

n = int(input())
fun(n)

你可能感兴趣的:(python入门,python,入门)