如何将字符串的最后一个字母移到最前面?

时间:2018-08-08 00:14:38

标签: python string

我正在进行groklearning方面的挑战,但是我似乎不知道该怎么做。

我的程序需要做一些事情:

  1. 检查单词是否以ay结尾,是否这样做:
  2. 从单词的末尾删除ay
  3. 将(现在)最后一个字母移到单词的开头。
  4. 打印出新单词。

我不知道如何将字母移到最前面。到目前为止,这是我的代码:

word = input('Word: ') 
if 'ay' in word:
  word1 = word[-1] + word[:-1]
  word2 = word1[2:]
  word3 = word2[-1] + word2[:-1] 
  print(word3)
else:
  print(word)

如果我输入“ athsmay”作为输入,它将发出“ athsm”。预先感谢!

1 个答案:

答案 0 :(得分:0)

您可以显式测试单词以>>> def rearrange(word): ... if word.endswith('ay'): ... word = word[-3] + word[:-3] ... return word ... >>> rearrange('athsmay') 'maths' 结尾,并在一行中进行串联:

word[-3]

根据您提供的规则:

  • 从头开始弹出“ ay”,给出“ athsm”
  • 将结果的最后一个字母移到最前面

word[-1]使用负索引,其中word[:-3]是单词中的最后一个字母。 // Typescript 2.x export function oldMethod<TProps>() { function create< TInstance extends Geometry | BufferGeometry, >( geometryClass: new () => TInstance, ): any; function create< TInstance extends Geometry | BufferGeometry, TKey1 extends Extract<keyof TProps, string>, >( geometryClass: new (param1: TProps[TKey1]) => TInstance, key1: TKey1, ): any; function create< TInstance extends Geometry | BufferGeometry, TKey1 extends Extract<keyof TProps, string>, TKey2 extends Extract<keyof TProps, string>, >( geometryClass: new (param1: TProps[TKey1], param2: TProps[TKey2]) => TInstance, key1: TKey1, key2: TKey2, ): any; function create< TInstance extends Geometry | BufferGeometry, TKey1 extends Extract<keyof TProps, string>, TKey2 extends Extract<keyof TProps, string>, TKey3 extends Extract<keyof TProps, string>, >( geometryClass: new (param1: TProps[TKey1], param2: TProps[TKey2], param3: TProps[TKey3]) => TInstance, key1: TKey1, key2: TKey2, key3: TKey3, ): any; // ...all the way up to 8 possible keys function create<TInstance extends Geometry | BufferGeometry>( geometryClass: new (...args: Array<TProps[Extract<keyof TProps, string>]>) => TInstance, ...args: Array<Extract<keyof TProps, string>>) { class GeneratedGeometryWrapper extends GeometryWrapperBase<TProps, TInstance> { protected constructGeometry(props: TProps): TInstance { return new geometryClass(...args.map((arg) => props[arg])); } } return class GeneratedGeometryDescriptor extends WrappedEntityDescriptor<GeneratedGeometryWrapper, TProps, TInstance, GeometryContainerType> { constructor() { super(GeneratedGeometryWrapper, geometryClass); this.hasRemountProps(...args); } }; } return create; } 是直至但不包括该字母的切片。