python 字符串

#######################字符串和转义字符###################################

字符串是 Python 中最常用的数据类型。我们可以使用引号('或")来创建字符串。

在需要在字符中使用特殊字符时,python用反斜杠(\)转义字符。

有时我们并不想让转义字符生效,我们只想显示字符串原来的意思,这就要用r和R来定义原始字符串。如:

print r'\t\r'

实际输出为“\t\r”。

###########################字符串的特性######################################

# 索引

```

>>> s = "hello"
# 正向索引
>>> s[1]
'e'
>>> s[0]
'h'
>>> s[4]
'o'

# 反向索引
>>> s = "hello world"
>>> s[-1]
'd'
>>> s[-2]
'l'
>>> s[-3]
'r'


```
# 切片
s[start:end:step]   # 从start开始到end-1结束, 步长为step;
    - 如果start省略, 则从头开始切片;
    - 如果end省略, 一直切片到字符串最后;
s[1:]
s[:-1]
s[::-1]    # 对于字符串进行反转
s[:]         # 对于字符串拷贝

# 成员操作符

```

>>> s = "hello"
>>> 'h' in s
True
>>> 'hel' in s
True
>>> 'oo' in s
False
>>> 'h' not in s
False
>>> 'oo' not in s
True

```

# 字符串连接


```
>>> a = "hello"
>>> b = "python"
>>> print("%s %s" %(a, b))
hello python
>>> a + b
'hellopython'
>>> a + " " +b
'hello python'


```

# 字符串的重复

 

```
>>> "*"*10 + "学生管理系统" + "*"*10
'**********\xe5\xad\xa6\xe7\x94\x9f\xe7\xae\xa1\xe7\x90\x86\xe7\xb3\xbb\xe7\xbb\x9f**********'
>>> print("*"*10 + "学生管理系统" + "*"*10)
**********学生管理系统**********

```

##################字符串常用方法_大小写##################

"""

'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper'
lower, upper, title

 


>>> "Hello".istitle()
True
>>> "hello".istitle()
False
>>> "HelloWorld".istitle()
False
>>> help("HelloWorld".istitle)

>>> "hello".upper()
'HELLO'
>>> "heLlo".lower()
'hello'
>>> "heLlo".title()
'Hello'
>>> "heLlo".swapcase()
'HElLO'


"""

################练习—回文数判断############

"""
 
##  题目要求:
判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样
的整数。

## 示例:

示例 1:  
        输入: 121
        输出: true
示例 2:  
        输入: -121
        输出: false
        解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。

示例 3:  
        输入: 10
        输出: false
        解释: 从右向左读, 为 01 。因此它不是一个回文数。

"""

num = input("num:")
if num == num[::-1]:
    print("%s是回文数" %(num))
else:
    print("%s不是回文数" %(num))

##################开头和结尾匹配####################

"""
endswith
startswith


"""

filename = "hello.log"
if filename.endswith(".log"):
    print(filename)
else:
    print("error file")


url1 = "file:///mnt"
url2 = "ftp://172.25.254.250/pub/"
url3 = "http://172.25.254.250/index.html"

 

if url1.startswith("http://"):
    print("爬取网页.......")
else:
    print("不能爬取网页")

##################### 去掉左右两边的空格 ##############

"""

strip      #去掉左右两边空格
lstrip    #去掉左边空格
rstrip     #去掉右边空格
# 注意: 去除左右两边的空格, 空格为广义的空格, 包括: \n, \t, \r


>>> s = "      hello     "
>>> s.strip()
'hello'
>>> s.lstrip()
'hello     '
>>> s.rstrip()
'      hello'
>>> s = "\nhello     "
>>> s.strip()
'hello'
>>> s = "\thello     "
>>> s.strip()
'hello'


>>> s = "helloh"
>>> s.strip('h')
'ello'
>>> s.strip('he')
'llo'
>>> s.lstrip('he')
'lloh'


center, ljust, rjust

 

>>> print("学生管理系统".center(50, '*'))
****************学生管理系统****************
>>> print("学生管理系统".ljust(50, '*'))
学生管理系统********************************
>>> print("学生管理系统".rjust(50, '*'))
********************************学生管理系统


"""

######################判断变量名是否合法################

"""

# 变量名是否合法?
# #
# # 变量名可以由字母,数字或者下划线;
# # 变量名只能以字母或者下划线开头;
#
# s = "hello@"
#
# 1. 判断变量名的第一个元素是否为字母或者下划线; s[0]
# 2. 如果第一个元素符合条件, 判断除了第一个元素的其他元素;s[1:]   


"""


# 1. 变量名的第一个字符是否为字母或者下划线?
# 2. 如果是, 继续判断(****);---参考4
# 3. 如果不是, 报错, 不合法;


# 4. 依次判断除了第一个字符之外的其他字符;
# 5. 判断是否为字母数字或者下划线

# eg: "h@ello@"

while True:
    s = input("变量名")
    if s == 'exit':
        print("欢迎下次使用.......")
        break
    if s[0].isalpha() or s[0] == "_":
        for i in    s[1:]:
            if not (i.isalnum() or i == "_"):
                print("%s变量名不合法" % (s))
                break
        else:
            print("%s变量名合法" % (s))
    else:
        print("%s变量名不合法" % (s))

################字符串练习_菱形###############

"""
编写程序, 输出星号组成的菱形.

练习知识点:
    for循环, 字符串center, 字符串重复

"""

a = int(input("num:"))
for i in range(1,a):
    print((' * '*i).center(3*a))
for i in range(a,0,-1):
    print((' * '*i).center(3*a))

#########################字符串的搜索和替换##################

"""
find:
replace:
count:


>>> s = "hello python , learn python"
>>> s.find('python')
6
>>> s.rfind('python')
21
>>> s.replace('python', 'linux')
'hello linux , learn linux'
>>> s
'hello python , learn python'
>>> s1 = s.replace('python', 'linux')
>>> s1
'hello linux , learn linux'
>>> s
'hello python , learn python'

>>> s.count("python")
2
>>> s.count("p")
2
>>> s.count("i")
0

"""

####################字符串的分离与拼接##################

"""
split:
join:


>>> ip = "172.25.254.19"
>>> ip1 = "1172.25.254.19"
>>> help(ip1.split)

>>> ip1.split('.')
['1172', '25', '254', '19']
>>> date = "2018-2-30"
>>> date.split("-")
['2018', '2', '30']
>>> date.replace('-', '/')
'2018/2/30'
>>> ip = ['1172', '25', '254', '19']
>>> "".join(ip)
'11722525419'
>>> ":".join(ip)
'1172:25:254:19'
>>> "*".join(ip)
'1172*25*254*19'

"""

#######################常用内置方法###################

"""

>>> min(2,4)
2
>>> max(2,5)
5
>>> sum(range(1,101))
5050
>>> sum(range(2,101,2))
2550
>>> sum(range(1,101,2))
2500

 

# 枚举: 返回索引值和对应的value值;
>>> for i,v in enumerate('hello'):  
...     print(str(i) +" -----> " + v)
...
0 -----> h
1 -----> e
2 -----> l
3 -----> l
4 -----> o

# zip
>>> s1 = 'abc'
>>> s2 = "123"
>>> for i in zip(s1,s2):
...     print(i)
...
('a', '1')
('b', '2')
('c', '3')
>>> for i in zip(s1,s2):
...     print("".join(i))
...
a1
b2
c3
>>> for i in zip(s1,s2):
...     print("-".join(i))
...
a-1
b-2
c-3

 

"""

######################### 小米笔试编程题 ##############

"""

3. # (2017-小米-句子反转)


- 题目描述:
> 给定一个句子(只包含字母和空格), 将句子中的单词位置反转,单词用空格分割, 单词之间只有一个空格,前>后没有空格。 比如: (1) “hello xiao mi”-> “mi xiao hello”

- 输入描述:
> 输入数据有多组,每组占一行,包含一个句子(句子长度小于1000个字符)

- 输出描述:
> 对于每个测试示例,要求输出句子中单词反转后形成的句子


- 示例1:

```
- 输入
    hello xiao mi
- 输出
    mi xiao hello


"""

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

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值