Python中字符串的使用

索引

s = 'abcde'
print(s[0])

切片

print(s[0:3]) #[start:end:step]
print(s[0:4:2])  第零个到第三个
print(s[:]) 全部
print(s[::-1])	反转
print(s[-1]) 倒数第一个
print(s[:-1]) 开始到倒数第二个
print(s[-3:-1]) 倒数第三个到倒数第二个
print(s[-3:]) 倒数第三个到结尾

拼接

a = 'a'
b = 'b'
print(a+' '+b)

字符串方法

a.isdigit()	是否是数字
a.istitle()	是否是标题(首字母大写)
a.upper()	转大写
a.lower()	转小写
a.isupper()	是否是大写
a.islower()	是否是小写
a.isalpha()	判断英文字母
a.isalnum()	是否是字母
a.endwith('.log')	是否是以.log结尾
a.startwith('http://')	是否以http://开头
a.strip()	去除两边的空格
s.lstrip()	去除左边的空格
s.rstrip()	去除右边的空格
s.strip('h')	去除两边的h字母

判断输入是否符合变量命名规则

while True:
    InputWord = input("Please input the variable's name:")
    Length = len(InputWord)
    if Length == 0:
        continue
    else:
        if InputWord[0].isalpha() == 1 or InputWord[0] == '_':
            for N in range(1,Length):
                if InputWord[N].isalnum() != 1 and InputWord[N] != '_':
                    print("Your input is illegal.")
                    break

            else:
                print("Your input is legal.")
        else:
            print("Your input is illegal.")

字符串统计

# PAL组成字符串,字符串中不超过一个A且不超过连续两个L
# PPALLP
# True
# ALLLPP
# False
#
# while True:
#     Input = input()
#     Input = Input.upper()
#     if Input.count('LLL') > 0 or Input.count('A') > 1:
#         print("False")
#     else:
#         print("True")
#

while True:
    Input = input()
    Input = Input.upper()
    print(not(Input.count('LLL') > 0 or Input.count('A') > 1))

输入以空格分割并反转

Input = input()
print(' '.join((Input.split()[::-1])))

输入A,B两字符串,求A-B

StrA = input()
StrB = input()
for n in StrB:
    StrA = StrA.replace(n, '')
print(StrA)
Python字符串是一种不可变的序列类型,用于表示文本数据。字符串可以通过单引号(')、双引号(")或三引号('''或""")来创建。三引号字符串可以跨越多行,常用于多行字符串和注释。 字符串Python是序列的一种,所以它支持一些通用的序列操作,比如索引、切片、乘法和成员资格测试等。 下面是字符串的一些常见操作: 1. 索引与切片:通过索引可以访问字符串的特定字符,通过切片可以获取字符串的一部分。 ```python s = "Hello, world!" print(s[0]) # 输出 'H' print(s[1:5]) # 输出 'ello' ``` 2. 字符串连接:可以使用加号(+)来连接两个字符串。 ```python s1 = "Hello" s2 = "world" print(s1 + ", " + s2) # 输出 'Hello, world' ``` 3. 重复:使用乘法操作符(*)可以重复字符串。 ```python print("Python" * 3) # 输出 'PythonPythonPython' ``` 4. 成员资格测试:使用in和not in来检查某个字符串是否包含在另一个字符串。 ```python print('H' in "Hello") # 输出 True print('z' not in "Python") # 输出 True ``` 5. 转义字符:在字符串可以使用反斜杠(\)来引入特殊字符,如换行(\n)、制表符(\t)等。 ```python print("Hello\nPython") # 输出 'Hello' 后跟一个换行,然后是 'Python' ``` 6. 原始字符串:在字符串前加上前缀r或R表示原始字符串,它不会处理字符串的转义字符。 ```python print(r"\n") # 输出 '\n' 而不是换行 ``` 7. 字符串方法:Python提供了许多字符串方法,例如upper(), lower(), split(), replace(), find(), format()等,用于处理字符串数据。 ```python s = "hello, world" print(s.upper()) # 输出 'HELLO, WORLD' print(s.split(",")) # 输出 ['hello', ' world'] ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值