Home > Software engineering >  How to print a string pattern?
How to print a string pattern?

Time:10-14

I have a string with characters and a number for the rows and columns that will be in the pattern:

char_str1 = 'abc'
char_str1 = '31452'
num = 5

I would like the output to be:

abcab       31452
bcabc       14523
cabca       45231
abcab       52314
bcabc       23145

I have tried doing:

for i in range(num):
   for j in range(num):
       print(char_str1, end='')
   print()
output:
abcabcabcabcabc
abcabcabcabcabc
abcabcabcabcabc
abcabcabcabcabc
abcabcabcabcabc

CodePudding user response:

If you replicate the strings at least num times, simple slicing works. The original strings need to be at least length 1 of course:

char_str1 = 'abc'
char_str2 = '31452'   # You had a typo here st1 instead of str2
num = 5

a = char_str1 * num
b = char_str2 * num

for i in range(num):
   print(a[i:i num], b[i:i num])

Output:

abcab 31452
bcabc 14523
cabca 45231
abcab 52314
bcabc 23145

CodePudding user response:

Please you below code in java for your patter!!

public class Main {
  public static void printPattern(String s, int n) {
    for (int i = 0; i < n; i  ) {
      for (int j = i; j < n   i; j  ) {
        System.out.print(s.charAt(j % s.length()));
      }
      System.out.println();
    }
  }
  public static void main(String[] args) {
    printPattern("abc", 5);
    printPattern("31452", 5);
  }
}
  • Related