Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 我不知道如何以两种不同的方式操纵字符串_Python_String - Fatal编程技术网

Python 我不知道如何以两种不同的方式操纵字符串

Python 我不知道如何以两种不同的方式操纵字符串,python,string,Python,String,我需要编写一个脚本,在这些模式中修改输入的字符串(但没有破折号。这些只是为了正确格式化): 我甚至不知道从哪里开始写这封信。用于索引每个字母: inputted="dinosaurs" In [25]: for i,c in enumerate(inputted,start=1): # set start to 1 instead of the default 0 print " "* i + c ' d i n

我需要编写一个脚本,在这些模式中修改输入的字符串(但没有破折号。这些只是为了正确格式化):

我甚至不知道从哪里开始写这封信。

用于索引每个字母:

inputted="dinosaurs"

In [25]: for i,c in enumerate(inputted,start=1): # set start to 1 instead of the default 0
            print " "* i + c ' 

     d
      i
       n
        o
         s
          a
           u
            r
             s

这也将有助于你理解问题的第二部分。

我将把它分为三个部分,每种格式一个。首先,从导入开始,从标准输入读取单词

from __future__ import print_function
import sys
import math

word = sys.argv[1]
1.边距随字符串长度的增加而增加 2.边距随着到字符串中间距离的增加而减小 我们创建一个函数来计算从单词末端到单词末端的距离,并使用它相应地添加正确数量的空格

distance = lambda i: len(word) / 2 - int(math.fabs((len(word) / 2) - i))
for i, character in enumerate(word):
    print(distance(i) * " ", character, sep='')
3.单词显示为三角形,单词中间位于底部。 对于最后一个,我们必须测试单词是否为奇数字符,如果是,则添加一个偏移量。我们使用此偏移来正确对齐中间字符。我们还重新定义了
distance
函数,以指示从单词中间到单词末尾的距离

distance = lambda i: int(math.fabs((len(word) / 2.) - i)) - 1
if len(word) % 2 == 1:
    offset = 1
else:
    offset = 0

for i in range(len(word) / 2 + offset):
    if i == len(word) - i - 1:
        print((i - offset) * " ", word[i])
    else:
        print(i * " ", word[i], (2 * distance(i) + offset) * " ", word[len(word) - i - 1], sep='')
编辑:这里是以“恐龙”作为输入运行程序的输出

d
 i
  n
   o
    s
     a
      u
       r
        s

d
 i
  n
   o
    s
   a
  u
 r
s

d       s
 i     r
  n   u
   o a
    s

最后一种解释是什么?代码格式比连字符更适用于此。这是一个带大括号的按钮。您需要从获取输入的长度开始,这里有一个函数
len()
。然后你可以开始在循环中计数,以决定要放入多少空格来进行适当的缩进。你是说你想用n+1空格填充第n个字母吗?使用lambda可能会出现严重的重复?op无法找出如何打印带有空格的字母,而您使用的是这样的代码?我也已经用枚举法回答了。
distance = lambda i: int(math.fabs((len(word) / 2.) - i)) - 1
if len(word) % 2 == 1:
    offset = 1
else:
    offset = 0

for i in range(len(word) / 2 + offset):
    if i == len(word) - i - 1:
        print((i - offset) * " ", word[i])
    else:
        print(i * " ", word[i], (2 * distance(i) + offset) * " ", word[len(word) - i - 1], sep='')
d
 i
  n
   o
    s
     a
      u
       r
        s

d
 i
  n
   o
    s
   a
  u
 r
s

d       s
 i     r
  n   u
   o a
    s