Python (1) Basic String Operations

First, remove the string spaces

s = '   abcf hgklj  '
s.strip() // 去除左右空格
s.lstrip() //去除左空格
s.rstrip() //去除右空格

2. String concatenation

s1 = 'abc'
s2 = 'def'
s1+s2

3. Upper and lower case

s = 'avc def'
s.upper() 全部改成大写
s.lower() 全部改成小写
s.capitalize() 首字母大写

Fourth, the location comparison

s_1 = 'abcdefg'
s_2 = 'abdeffxx'
print(s_1.index('bcd'))
print(s_2.index('bcd'))//异常 因为s_2中没有bcd

5. Catch exceptions

try:
    print(s_2.index('bcd'))
except ValueError:
    pass //忽略异常

6. Compare
//The cmp function in python3 is removed

print(s_1 == s_2)
print(s_1 < s_2)
print(s_1 > s_2)

7. Find the length

len('abc')

Eight, empty string is equivalent to false

s = ' '
if not s:
    print('Empty')

Nine, character segmentation and connection

s = 'abc,def,ghi'
splitted = s.split(',')
print(type(splitted)) //输出list
print(splitted)//输出['abc','def','ghi']

Split characters by line

s = """abc
def
ghi"""
s_1 = s.split('\n')//第一种方法
s_2 = s.splitlines() //第二种方法

connect

s = ['abc','def','ghi']
print(''.join(s))//输出abcdefghi
print('-'.join(s))//输出abc-def-ghi
print('\n'.join(s))//输出abc
                         def
                         ghi

10. Strings are commonly used to judge
startswith()
to judge whether a string starts with a certain character

s = 'abcdefg'
print(s.startswith('abc'))//返回True
print(s.endswith('efg')
//其他的一些判断用法
print('123456abcd'.isalnum())
print('\t12ab'.islanum())
print('abcd'.isalpha())
print('1234'.isdigit())
print('    '.isspace())
print('abcd1234'.islower())
print('abcd1234'.isupper())
print('Hello World'.istitle())

11. Conversion between strings and numbers

数字到字符串的转化
print(str(5))
print(str(5.))//后面自动补0
print(str(-5.23))
字符串到数字
print(int('1234'))
print(float('1234.34'))
二进制转换为十进制
print(int('110111',2))
十六进制转化为十进制
print(int('ffff',16))

Twelve, the string cannot be modified, put the string into an array

s = 'abcdefg'
l = list(s)
print(l)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324603969&siteId=291194637