Python之字符串

在 Python 中,用引号(单引号/双引号)括起的都是字符串,如:

"This is a string"
'This is also a string'

修改字符串大小写的方法

1.将每个单词的首字母都改为大写:title()

str = "hello worold"
print(str.title())        #这里输出:Hello World
print(str)                #这里输出:hello world        (注意:字符串本身并未改变)

2.将字符串改为全部大写:upper()

str = "hello world"
print(str.upper())            #这里输出:HELLO WORLD
print(str)                    #这里输出:hello world        (注意:字符串本身并未改变)

3.将字符串改为全部小写:lower()

str = "Hello World"
print(str.lower())        #这里输出:hello world
print(str)                #这里输出:Hello World        (注意:字符串本身并未改变)

4.合并(拼接)字符串:使用加号(+)

str1 = "hello"
str2 = "world"
str3 = str1 + " " + str2

print(str3)                     #这里输出:hello world
print(str3.title() + " !")      #这里输出:Hello World !

5.使用制表符或换行符添加空白

跟C/C++一样,字符组合 "\t"代表制表符;字符组合 "\n"代表制表符;

6.删除字符串中的空白

去掉符串首部空白字符: lstrip()

去掉符串末尾空白字符: rstrip()    

去掉符串两端空白字符: strip()    

--------注意:此时是暂时性删除掉字符串末尾的字符串,想要永久删除,还是将其结果返回到相应的变量中

str = "    hello    "

print(str)                    #输出:‘    hello    ’
#临时删除字符串首部空白字符
print(str.lstrip())           #输出:‘hello    ’
print(str)                    #输出:‘    hello    ’
#临时删除字符串末尾空白字符
print(str.rstrip())           #输出:‘    hello’
print(str)                    #输出:‘    hello    ’
#临时删除字符串两端空白字符
print(str.strip())            #输出:‘hello’
print(str)                    #输出:‘    hello    ’
#永久删除字符串两端空白字符
str = str.strip();
print(str)                    #输出:‘hello’

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值