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)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值