华为机试题:HJ4 字符串分隔(python)

文章目录

  • 知识点详解
    • 1、len():返回字符串、列表、字典、元组等长度。
    • 2、ljust():左对齐文本。向指定字符串的右侧填充指定字符。
    • 3、rjust():右对齐文本。向指定字符串的左侧填充指定字符。
    • 4、center():居中对齐文本。

描述
•输入一个字符串,请按长度为8拆分每个输入字符串并进行输出;
•长度不是8整数倍的字符串请在后面补数字0,空字符串不处理。

输入描述:连续输入字符串(每个字符串长度小于等于100)

输出描述:依次输出所有分割后的长度为8的新字符串

示例1

输入:abc
输出:abc00000

Python3

while True:
    try: 
        s=input()            
        while len(s)>8:                
            print(s[:8])                
            s=s[8:]            
        print(s.ljust(8,"0"))
    except:
        break
        
  • input():用于获取控制台的输入。
  • len():返回字符串、列表、字典、元组等长度。
  • ljust():左对齐文本。向指定字符串的右侧填充指定字符。
  • print() :用于打印输出。

知识点详解

1、len():返回字符串、列表、字典、元组等长度。

str_temp = "Hello, boy !"
print(len(str_temp))                    # 【输出结果】12
#############################################
list_temp = ['h', 'e', 'l', 'l', 'o']
print(len(list_temp))                   # 【输出结果】5
#############################################
dict_temp = {'num': 520, 'name': "do do"}
print(len(dict_temp))                   # 【输出结果】2
#############################################
tuple_temp = ('G', 'o', 'o', 'd')
print(len(tuple_temp))                  # 【输出结果】4

2、ljust():左对齐文本。向指定字符串的右侧填充指定字符。

str.ljust(width, fillchar)
输入参数:

  • (1)str:表示要进行填充的字符串;
  • (2)width:表示包括 str 本身长度在内,字符串要占的总长度;
  • (3)fillchar:指定填充字符串时所用的字符,默认情况使用空格(可选参数)。
S = 'www.baidu.com'
addr = 'http://www.baidu.com'
print(S.ljust(35,'-'))			# 【输出结果】www.baidu.com--------------------
print(addr.ljust(35,'-'))		# 【输出结果】http://www.baidu.com-------------

3、rjust():右对齐文本。向指定字符串的左侧填充指定字符。

str.rjust(width, fillchar)
输入参数:

  • (1)str:表示要进行填充的字符串;
  • (2)width:表示包括 str 本身长度在内,字符串要占的总长度;
  • (3)fillchar:指定填充字符串时所用的字符,默认情况使用空格(可选参数)。
S = 'http://www.baidu.com/python'
addr = 'http://www.baidu.com'
print(S.rjust(35,'-'))			# 【输出结果】-----http://www.baidu.com/python
print(addr.rjust(35,'-'))		# 【输出结果】------------http://www.baidu.com

4、center():居中对齐文本。

str.center(width, fillchar)
输入参数:

  • (1)str:表示要进行填充的字符串;
  • (2)width:表示包括 str 本身长度在内,字符串要占的总长度;
  • (3)fillchar:指定填充字符串时所用的字符,默认情况使用空格(可选参数)。
S = 'http://www.baidu.com/python/'
addr = 'http://www.baidu.com'
print(S.center(35, '-'))			# 【输出结果】----http://www.baidu.com/python/---
print(addr.center(35, '-'))			# 【输出结果】--------http://www.baidu.com-------

你可能感兴趣的:(华为机试题,python,开发语言)