Thursday, January 7, 2021

Python Strings Interview questions - Multiple choice

Strings:

===============================================

 1. What will be the output of the following Python statement?

"a"+"bc"

a) a

b) bc

c) bca

d) abc

Answer: d

Explanation: + operator is concatenation operator.

 

2. What will be the output of the following Python statement?

>>>"abcd"[2:]

a) a

b) ab

c) cd

d) dc


Answer: c

Explanation: Slice operation is performed on the string.


3. What will be the output of the following Python code?

>>> str1 = 'hello'

>>> str2 = ','

>>> str3 = 'world'

>>> str1[-1:]


a) olleh

b) hello

c) h

d) o

 

Answer: d

Explanation: -1 corresponds to the last index.


 4. What arithmetic operators can be used with strings?

a) +

b) *

c) –

d) All of the mentioned

 

Answer: a

Explanation: + is used to concatenate.


5. What will be the output of the following Python code?

>>>print (r"\nhello")

a) a new line and hello

b) \nhello

c) the letter r and then hello

d) error

 

Answer: b

Explanation: When prefixed with the letter ‘r’ or ‘R’ a string literal becomes a raw string and the escape sequences such as \n are not converted.

 

6. What will be the output of the following Python statement?

>>>print('new' 'line')

a) Error

b) Output equivalent to print ‘new\nline’

c) newline

d) new line

 

Answer: c

Explanation: String literal separated by whitespace are allowed. They are concatenated.


7. What will be the output of the following Python code?

>>>str1="helloworld"

>>>str1[::-1]

a) dlrowolleh

b) hello

c) world

d) helloworld

 

Answer: a

Explanation: execute in reverse

 

8. print(0xA + 0xB + 0xC):

a) 0xA0xB0xC

b) Error

c) 0x22

d) 33

 

Answer: d

Explanation: 0xA and 0xB and 0xC are hexadecimal integer literals representing 

the decimal values 10, 11 and 12 respectively. There sum is 33.


9. What will be the output of the following Python code?

>>>example = "snow world"

>>>print(example[5:7])

a) wo

b) world

c) sn

d) rl

 

Answer: a

Explanation: Execute in the shell and verify.


10. What will be the output of the following Python code?

>>>example = "snow world"

>>>example[3] = 's'

>>>print(example)

a) snow

b) snow world

c) Error

d) snos world


Answer: c

Explanation: Strings cannot be modified,


11. What will be the output of the following Python code?

>>>max("what are you")

a) error

b) u

c) t

d) y

 

Answer: d

Explanation: Max returns the character with the highest ASCII value.


12. Given a string example=”hello” what is the output of example.count(‘l’)?

a) 2

b) 1

c) None

d) 0

 

Answer: a

Explanation: l occurs twice in hello.

 

13. What will be the output of the following Python code?

>>>example = "helle"

>>>example.find("e")

a) Error

b) -1

c) 1

d) 0

 

Answer: c

Explanation: Returns the lowest index.

 

14. What will be the output of the following Python code?

>>>example = "helle"

>>>example.rfind("e")

a) -1

b) 4

c) 3

d) 1

 

Answer: b

Explanation: It will start the search from the right side,  but the index will give from the 0th index.

   

15. What will be the output of the following Python code?

>>>example="helloworld"

>>>example[::-1].startswith("d")

a) dlrowolleh

b) True

c) -1

d) None

 

Answer: b

Explanation: Starts with checks if the given string starts with the parameter that is passed.

16. Which of the following statements prints hello\example\test.txt?

a) print(“hello\example\test.txt”)

b) print(“hello\\example\\test.txt”)

c) print(“hello\”example\”test.txt”)

d) print(“hello”\example”\test.txt”)

 

Answer: b

Explanation: \t consider as  escape sequence character. Here we have 3 possibilities

        1. we have to use \\"string"

        2. we have to use raw_path ("string") function

        3. we have to use r"string"  which means raw string         

17. Suppose data is “\t\tWorld\n”, what is data.strip()?

a) \t\tWorld\n

b) \t\tWorld\n

c) \t\tWORLD\n

d) World

 

Answer: d

Explanation: If we print data, we will get output as 4 spaces again 4 spaces & at the end of the string new line will print.  

strip() function will remove unwanted content on both sides (Note: by default input of strip() is space)

Ans: So it will remove spaces on both sides ---->World

18. The format function, when applied on a string returns ___________

a) Error

b) int

c) bool

d) str

 

Answer: d

Explanation: Format function returns a string.

19. What will be the output of the “hello” +1+2+3?

a) hello123

b) hello

c) Error

d) hello6

 

Answer: c

Explanation: Cannot concatenate str and int objects.

20. What will be the output of the following Python code?

>>>print("D", end = ' ')

>>>print("C", end = ' ')

>>>print("B", end = ' ')

>>>print("A", end = ' ')

a) DCBA

b) A, B, C, D

c) D C B A

d) D, C, B, A will be displayed on four lines

 

Answer: c

Explanation: Execute in the shell.

21. Say s=”hello” what will be the return value of type(s)?

a) int

b) bool

c) str

d) String

 

Answer: c

Explanation: str is used to represent strings in python.

 

22. What is “Hello”.replace(“l”, “e”)?

a) Heeeo

b) Heelo

c) Heleo

d) None

 

Answer: a

Explanation: Execute in shell to verify.

23. Suppose x is 345.3546, what is format(x, “10.3f”) (_ indicates space).

a) __345.3556

b) _______345.355

c) _______345

d) ___345.3546

 

Answer: b

Explanation: Execute in the shell to verify.

24.What will be the output of the following Python statement?(python 3.xx)

>>>print(format("Welcome", "10s"), end = '#')

>>>print(format(111, "4d"), end = '#')

>>>print(format(924.656, "3.2f"))

a) Welcome# 111#924.66

b) Welcome#111#924.66

c) Welcome#111#.66

d) Welcome   # 111#924.66

 

Answer: d

Explanation: Execute in the shell to verify.

 

25. What will be the output of the following Python code?

print("abc DEF".capitalize())

a) abc def

b) ABC DEF

c) Abc def

d) Abc Def

 

Answer: c

Explanation: The first letter of the string is converted to uppercase and the others are converted to lowercase.

26. What will be the output of the following Python code?

print("abcdef".center())

a) cd

b) abcdef

c) error

d) none of the mentioned

 

Answer: c

Explanation: The function center() takes at least one parameter.

27. What will be the output of the following Python code?

print("abcdef".center(0))

a) cd

b) abcdef

c) error

d) none of the mentioned

 

Answer: b

Explanation: The entire string is printed when the argument passed to center() is less than the length of the string.

"""

Regarding Pading concept:

Note1: If the width value is Even number, Fill characters will be added 1st right-hand side then remaining at left-hand
Note2: If the width value is Odd number, Fill characters will be added 1st left-hand side then remaining at right-hand
"""

28.  What will be the output of the following Python code? (padding concept)

print("abcdef".center(7, '1'))

a) 1abcdef

b) abcdef1

c) abcdef

d) error

 

Answer: a

Explanation: The character ‘1’ is used for padding instead of a space.

 

29. What will be the output of the following Python code?  (padding concept)

print("abcdef".center(7, 1))

a) 1abcdef

b) abcdef1

c) abcdef

d) error

 

Answer: d

Explanation: TypeError, the fill character must be a character, not an int.

30. What will be the output of the following Python code?

print("abcdef".center(10, '12'))

a) 12abcdef12

b) abcdef1212

c) 1212abcdef

d) error

 

Answer: d

Explanation: The fill character must be exactly one character long.

31. What will be the output of the following Python code?

print("xyyzxyzxzxyy".count('yy'))

a) 2

b) 0

c) error

d) none of the mentioned

 

Answer: a

Explanation: Counts the number of times the substring ‘yy’ is present in the given string.

 

32. What will be the output of the following Python code?

print("xyyzxyzxzxyy".count('yy', 1))

a) 2

b) 0

c) 1

d) none of the mentioned

 

Answer: a

Explanation: Counts the number of times the substring ‘yy’ is present in the given string, starting from position 1.

33. What will be the output of the following Python code?

print("xyyzxyzxzxyy".count('xyy', 2, 11))

a) 2

b) 0

c) 1

d) error

 

Answer: b

Explanation: Counts the number of times the substring ‘xyy’ is present in the given string,

starting from position 2 and ending at position 11


34. What will be the output of the following Python code?

print("xyyzxyzxzxyy".count('xyy', 0, 100))

a) 2

b) 0

c) 1

d) error

 

Answer: a

Explanation: An error will not occur if the end value is greater than the length of the string itself.

35. What will be the output of the following Python code?

print("xyyzxyzxzxyy".count('yy', 2))

a) 2

b) 0

c) 1

d) none of the mentioned

 

Answer: c

Explanation: Counts the number of times the substring ‘yy’ is present in the given string, starting from position 2.

36. What will be the output of the following Python code?

print("xyyzxyzxzxyy".count('xyy', -10, -1))

a) 2

b) 0

c) 1

d) error

 

Answer: b

Explanation: Counts the number of times the substring ‘xyy’ is present in the given string, 

starting from position 2 and ending at position 11.

 

37. What will be the output of the following Python code?

print('xyz'.encode())

a) XYZ    

b) ‘xyz’

c) b’’xyz

d) h’xyz’

 

Answer: c

Explanation: By default, Data transmission from source to destination happens in the binary format (8 bits /sec == 1 byte ==utf-8 encoding), so that  A byte object is returned by encode.

38. What is the default value of encoding in encode()?

a) ascii

b) qwerty

c) utf-8

d) utf-16

 

Answer: c

Explanation: The default value of encoding is utf-8.

39. What will be the output of the following Python code?

print("xyyzxyzxzxyy".endswith("xyy"))

a) 1

b) True

c) 3

d) 2

 

Answer: b

Explanation: The function returns True if the given string ends with the specified substring.

40. What will be the output of the following Python code?

print("xyyzxyzxzxyy".endswith("xyy", 0, 2))

a) 0

b) 1

c) True

d) False


Answer: d

Explanation: The function returns False if the given string does not end with 

the specified substring.


41. What will be the output of the following Python code?

print("abcdef".find("cd") == "cd" in "abcdef")

a) True

b) False

c) Error

d) None of the mentioned

 

Answer: b

Explanation: The function find() returns the position of the substring in 

the given string whereas the in keyword returns a value of Boolean type.

42 What will be the output of the following Python code?

print("abcdef".find("cd"))

a) True

b) 2

c) 3

d) None of the mentioned


Answer: b

Explanation: The first position in the given string at which 

the substring can be found is returned.

43. What will be the output of the following Python code?

print("ccdcddcd".find("c"))

a) 4

b) 0

c) Error

d) True


Answer: b

Explanation: The first position in the given string at which 

the substring can be found is returned.

 

44. What will be the output of the following Python code?

print("Hello {0} and {1}".format('swetha', 'meera'))

a) Hello swetha and meera

b) Hello {0} and {1} swetha meera

c) Error

d) Hello 0 and 1

 

Answer: a

Explanation: The numbers 0 and 1 represent the position at which the strings are present.

45. What will be the output of the following Python code?

print("Hello {1} and {0}".format('bin', 'foo'))

a) Hello foo and bin

b) Hello bin and foo

c) Error

d) None of the mentioned

 

Answer: a

Explanation: The numbers 0 and 1 represent the position at which the strings are present.


46. What will be the output of the following Python code?

print("Hello {} and {}".format('foo', 'bin'))

a) Hello foo and bin

b) Hello {} and {}

c) Error

d) Hello and

 

Answer: a

Explanation: It is the same as Hello {0} and {1}.


47. What will be the output of the following Python code?

print("Hello {name1} and {name2}".format('foo', 'bin'))

a) Hello foo and bin

b) Hello {name1} and {name2}

c) Error

d) Hello and

 

Answer: c

Explanation: The arguments passed to the function format aren’t keyword arguments.

48. What will be the output of the following Python code?

print("Hello {name1} and {name2}".format(name1='foo', name2='bin'))

a) Hello foo and bin

b) Hello {name1} and {name2}

c) Error

d) Hello and

 

Answer: a

Explanation: The arguments are accessed by their names.

49. What will be the output of the following Python code?

print("Hello {0!r} and {0!s}".format('foo', 'bin'))

a) Hello foo and foo

b) Hello ‘foo’ and foo

c) Hello foo and ‘bin’

d) Error

 

Answer: b

Explanation: !r -->  means  "raw string"    &   !s--> means normal string 

50. What will be the output of the following Python code?

print("Hello {0} and {1}".format(('foo', 'bin')))

a) Hello foo and bin

b) Hello (‘foo’, ‘bin’) and (‘foo’, ‘bin’)`

c) Error

d) None of the mentioned

 

Answer: c

Explanation: IndexError, the tuple index is out of range.

51. What will be the output of the following Python code?

    print("Hello {0[0]} & {0[1]} and {1} ".format(('Nanditha', 'Venkat'), "Raahi"))                          

        a) Hello Nanditha  &  Venkat 

b) Hello Nanditha &  Venkat and Raahi 

c) Error

d) None of the mentioned

 

Answer: a

Explanation: The elements of the tuple are accessed by their indices.


52. What will be the output of the following Python code snippet?

print('The sum of {0} and {1} is {2}'.format(2, 10, 12))

a) The sum of 2 and 10 is 12

b) Error

c) The sum of 0 and 1 is 2

d) None of the mentioned

 

Answer: a

Explanation: The arguments passed to the function format can be integers also.


53. What will be the output of the following Python code snippet?

print('The sum of {0:b} and {1:x} is {2:o}'.format(2, 10, 12))

a) The sum of 2 and 10 is 12

b) The sum of 10 and a is 14

c) The sum of 10 and a is c

d) Error

 

Answer: b

Explanation: 2 is converted to binary, 10 to hexadecimal and 12 to octal.

 

54. What will be the output of the following Python code?

print('ab12'.isalnum())

a) True

b) False

c) None

d) Error


Answer: a

Explanation: The string has only letters and digits.

55. What will be the output of the following Python code?

print('ab,12'.isalnum())


a) True

b) False

c) None

d) Error

 

Answer: b

Explanation: The character , is not a letter or a digit.

56. What will be the output of the following Python code?

print('ab'.isalpha())

a) True

b) False

c) None

d) Error


Answer: a

Explanation: The string has only letters.


57. What will be the output of the following Python code?

print('a B'.isalpha())


a) True

b) False

c) None

d) Error

 

Answer: b

Explanation: Space is not a letter.


58. What will be the output of the following Python code snippet?

print('0xa'.isdigit())


a) True

b) False

c) None

d) Error

 

Answer: b

Explanation: Hexadecimal digits aren’t considered as digits (a-f).


59. What will be the output of the following Python code snippet?

print(''.isdigit())


a) True

b) False

c) None

d) Error

 

Answer: b

Explanation: If there are no characters then False is returned.


60. What will be the output of the following Python code snippet?

print('my_string'.isidentifier())

a) True

b) False

c) None

d) Error


Answer: a

Explanation: It is a valid identifier.

61. What will be the output of the following Python code snippet?

print('__foo__'.isidentifier())


a) True

b) False

c) None

d) Error

 

Answer: a

Explanation: It is a valid identifier.

 

62. What will be the output of the following Python code snippet?

print('for'.isidentifier())


a) True

b) False

c) None

d) Error

 

Answer: a

Explanation: Even keywords are considered as valid identifiers.

63. What will be the output of the following Python code snippet?

print('abc'.islower())

a) True

b) False

c) None

d) Error

 

Answer: a

Explanation: There are no uppercase letters.


64. What will be the output of the following Python code snippet?

print('a@ 1,'.islower())

a) True

b) False

c) None

d) Error


Answer: a

Explanation: There are no uppercase letters.

65. What will be the output of the following Python code snippet?

print('11'.isnumeric())

a) True

b) False

c) None

d) Error

 

Answer: a

Explanation: All the characters are numeric.


66. What will be the output of the following Python code snippet?

print('1.1'.isnumeric())

a) True

b) False

c) None

d) Error

 

Answer: b

Explanation: The character . is not a numeric character.


67. What will be the output of the following Python code snippet?

print(''''''.isspace())

a) True

b) False

c) None

d) Error

 

Answer: b

Explanation: None.


68. What will be the output of the following Python code snippet?

print('\t'.isspace())

a) True

b) False

c) None

d) Error

 

Answer: a

Explanation: Tab Spaces are considered as spaces.

69. What will be the output of the following Python code snippet?

print('HelloWorld'.istitle())

a) True

b) False

c) None

d) Error

 

Answer: b

Explanation: The letter W is uppercased.

70. What will be the output of the following Python code snippet?

print('Hello World'.istitle())

a) True

b) False

c) None

d) Error

 

Answer: a

Explanation: It is in title form.


71. What will be the output of the following Python code?

print('1Rn@'.lower())

a) n

b) 1rn@

c) rn

d) r

 

Answer: b

Explanation: Uppercase letters are converted to lowercase. 

The other characters are left unchanged.

72. What will be the output of the following Python code?

print('''\tfoo'''.lstrip())

a) \tfoo

b) foo

c)   foo

d) none of the mentioned

 

Answer: b

Explanation: All leading whitespace is removed.

73. What will be the output of the following Python code?

print('xyyzxxyxyy'.lstrip('xyy'))

a) error

b) zxxyxyy

c) z

d) zxxy

 

Answer: b

Explanation: The leading characters containing xyy are removed.

74. What will be the output of the following Python code?

print('abcdef'.partition('cd'))

a) (‘ab’, ‘ef’)

b) (‘abef’)

c) (‘ab’, ‘cd’, ‘ef’)

d) 2

 

Answer: c

Explanation: The string is split into three parts by partition.

75. What will be the output of the following Python code?

print('abcdefcdgh'.partition('cd'))

a) (‘ab’, ‘cd’, ‘ef’, ‘cd’, ‘gh’)

b) (‘ab’, ‘cd’, ‘efcdgh’)

c) (‘abcdef’, ‘cd’, ‘gh’)

d) error

 

Answer: b

Explanation: The string is partitioned at the point where the separator first appears.

76. What will be the output of the following Python code?

print('abcd'.partition('cd'))

a) ('ab', 'cd', '')

b) (‘ab’, ‘cd’)

c) error

d) none of the mentioned

 

Answer: a

Explanation: The last item is a null string.

 

77. What will be the output of the following Python code snippet?

print('cd'.partition('cd'))

a) (‘cd’)

b) (”)

c) (‘cd’, ”, ”)

d) ('', 'cd', '')

 

Answer: d

Explanation: The entire string has been passed as the separator hence 

the first and the last item of the tuple returned are null strings.


78. What will be the output of the following Python code snippet?

print('abcdef12'.replace('cd', '12'))

a) ab12ef12

b) abcdef12

c) ab12efcd

d) none of the mentioned

 

Answer: a

Explanation: All occurrences of the first substring are replaced by the second substring.

79. What will be the output of the following Python code snippet?

print('abef'.replace('cd', '12'))

a) abef

b) 12

c) error

d) none of the mentioned

 

Answer: a

Explanation: The first substring is not present in the given string and hence nothing is replaced.


80. What will be the output of the following Python code snippet?

print('abcefd'.replace('cd', '12'))

a) ab1ef2

b) abcefd

c) ab1efd

d) ab12ed2

 

Answer: b

Explanation: The first substring is not present in the given string and hence nothing is replaced.

81. What will be the output of the following Python code snippet?

print('xyyxyyxyxyxxy'.replace('xy', '12', 3))

a) 12y12y12xyxxy

b) 12y12y1212x12

c) 12yxyyxyxyxxy

d) xyyxyyxyxyx12

 

Answer: a

Explanation: The first 0 occurrences of the given substring are replaced.

 

82. What will be the output of the following Python code snippet?

print('xyyxyyxyxyxxy'.replace('xy', '12', 100))

a) xyyxyyxyxyxxy

b) 12y12y1212x12

c) none of the mentioned

d) error

 

Answer: b

Explanation: The first 100 occurrences of the given substring are replaced, if 100 occurrences are not available then how many occurrences it's available those many times  it will be replaced with required string

83. What will be the output of the following Python code snippet?

print('abcdefcdghcd'.split('cd'))

a) [‘ab’, ‘ef’, ‘gh’]

b) [‘ab’, ‘ef’, ‘gh’, ”]

c) (‘ab’, ‘ef’, ‘gh’)

d) (‘ab’, ‘ef’, ‘gh’, ”)

 

Answer: b  

Explanation: The given string is split and a list of substrings is returned.  

Note : when we get at the ens then it will get empty string

84. What will be the output of the following Python code snippet?

print('abcdefcdghcd'.split('cd', 0))

a) [‘abcdefcdghcd’]

b) ‘abcdefcdghcd’

c) error

d) none of the mentioned

 

Answer: a

Explanation: The given string is split at 0 occurrences of the specified substring.

85. What will be the output of the following Python code snippet?

print('abcdefcdghcd'.split('cd', 2))

a) [‘ab’, ‘ef’, ‘ghcd’]

b) [‘ab’, ‘efcdghcd’]

c) [‘abcdef’, ‘ghcd’]

d) none of the mentioned

 

Answer: a

Explanation: The string is split into a maximum of maxsplit+1 substrings.

86. What will be the output of the following Python code snippet?

print('ab\ncd\nef'.splitlines())

a) [‘ab’, ‘cd’, ‘ef’]

b) [‘ab\n’, ‘cd\n’, ‘ef\n’]

c) [‘ab\n’, ‘cd\n’, ‘ef’]

d) [‘ab’, ‘cd’, ‘ef\n’]

 

Answer: a

Explanation: It is similar to calling split(‘\n’).

87. What will be the output of the following Python code snippet?

print('Ab!2'.swapcase())

a) AB!@

b) ab12

c) aB!2

d) aB1@

 

Answer: c

Explanation: Lowercase letters are converted to uppercase and vice-versa.

88. What will be the output of the following Python code snippet?

print('ab cd ef'.title())

a) Ab cd ef

b) Ab cd eF

c) Ab Cd Ef

d) None of the mentioned

 

Answer: c

Explanation: The first letter of every word is capitalized.

89. What will be the output of the following Python code snippet?

print('ab cd-ef'.title())

a) Ab cd-ef

b) Ab Cd-ef

c) Ab Cd-Ef

d) None of the mentioned

 

Answer: c

Explanation: The first letter of every word is capitalized. Special symbols terminate a word.


90. What will be the output of the following Python code snippet?

print('ab'.zfill(5))

a) 000ab

b) 00ab0

c) 0ab00

d) ab000

 

Answer: a

Explanation: The string is padded with zeros on the left-hand side. It is useful for formatting numbers.

91. What will be the output of the following Python code snippet?

print('+99'.zfill(5))

a) 00+99

b) 00099

c) +0099

d) +++99

 

Answer: c

Explanation: zeros are filled in between the first sign and the rest of the string.

92. What will be the output of the following Python statement?

>>>chr(ord('A'))

a) A

b) B

c) a

d) Error

 

Answer: a

Explanation: Execute in shell to verify.

93. What will be the output of the following Python statement?

>>>print(chr(ord('b')+1))

a) C

b) b

c) c

d) d

 

Answer: c

Explanation: Execute in the shell to verify.

94. What will be displayed by print(ord("g") - ord("a")) ?

a) 0

b) 6

c) 7

d) 2

 

Answer: b

Explanation:  ord() function will convert characters into ASCII values ord('a') ==>97 & ord('b') ==>98

 & char() function will convert  ASCII values into characters.

Hence the output of this code is 98-97, which is equal to 1.

95. To concatenate two strings to a third what statements are applicable?

a) s3 = s1 . s2

b) s3 = s1.add(s2)

c) s3 = s1.__add__(s2)

d) s3 = s1 * s2

 

Answer: c

Explanation: __add__ is another method that can be used for concatenation.


 96. The output of executing string.ascii_letters can also be achieved by:

a) string.ascii_lowercase_string.digits

b) abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

c) abcdefghijklmnopqrstuvwxyz

d) ABCDEFGHIJKLMNOPQRSTUVWXYZ

 

Answer: b

Explanation: Execute in the shell and check.


Request: If you find this information useful, please provide your valuable comments.


Friday, March 6, 2020

vi editor or vim editor in linux

                                      vi /vim-related Linux commands
 Note: To use vim tool/ Editor, we must install the command:  sudo apt-get install vim 
How to open a file?
vi file_name  ==> to open the file
Ex: vi narendra.log   / vi narendra.txt

How to modify a file's content? 
Open the file & (press insert / i ) to make modifications to that file,    
Do the modifications / add new content to the file, Then 
press (Esc button) then type(:wq! ) to save the file with modifications.

Directly how to go particular line a file?
 vi  <filename>  +13 To go for a particular line(13 / 72) while opening the file with vi editor 

If you don't know the file name exactly but if you remember the file name half, 
then you can open that file using vi *half file name*     Ex: vi *105*

How to move all the files  at a time a  particular Directory 
 use the * symbol (* means all)
Ex: If you move all files to another directory /destination path.
      mv <space> * <space> Destination_path
                           or 
     mv <space> Source_path/* <space> Destination_path

How to set line numbers in a file?
Esc :set nu or Esc :set number ==> command will set line numbers for your code
Esc :set nonu or Esc :set nonumber ==> command will remove line numbers for your code

How to copy multiple lines in a file?
<Number>yy   ==>  To copy the Number of lines in a file 
Example:    yy   ==>  To copy single line in file 
                 4yy   ==>  To copy 4 lines in a file

   p    ==> to paste copied lines at once
 3p    ==> to paste copied lines 3 times

How to perform undo in vi editor?
 u   ==> undo (undo any number of previous actions)

How to delete multiple lines in a file?
<Number>dd  ==> To delete the Number of lines in a file
Example:  dd   ==> To delete a single line (where your cursor is present)
                3dd  ==> To delete 3 lines from the cursor position

How to delete from a specific line to a specific line in a file without opening it.
command: sed <space> -i <space> 'starting line number, ending line numberd' <space> file_name
d means delete
Example : sed -i '567,670d' test_Cfm3Util_5.py

How to Search a particular word or content in a file? 
/pattern — Search forward for "pattern."
/(forward slash) 
/<word>    *** make sure that word is case sensitive ***
after that, use lower case n to search downwards from the current cursor position (Repeat the search in the same direction)
after that, use Upper case N to search downwards from the current cursor position (Repeat the search in the opposite direction.)
?pattern — Search backwards for "pattern."

<Number> Shift + <   ==> To move the Number of lines towards the left-hand side of a file 
Example:    Shift + <   ==> To move a single line towards the left-hand side of the file
                4 Shift + <   ==>  To move the Number of lines towards the left-hand side of the file 

<Number> Shift + >   ==> To move the Number of lines towards right-hand side of a file 
Example:    Shift + >   ==> To move a single line towards right-hand side of the file
                4 Shift + >   ==>  To move the Number of lines towards the right-hand side of the file

 Esc: set paste then paste your content by using p  (to paste precisely how the user copied content with indentation)

How to Replace a string ( single / multiple occurrences) in a file?

  • :s/old/new/ — Replace the first occurrence of "old" with "new" on the current line.
  • :s/old/new/g — Replace all occurrences of "old" with "new" on the current line.
  • :%s/old/new/g — Replace all occurrences of "old" with "new" in the entire file.

Request: If you find this information useful, please provide your valuable comments.

Optional Part 

How to delete lines in vi editor or vim editor in linu

Delete a single line in vi editor

The command to perform the deletion is dd, which is pressing the letter ‘d’ in quick succession twice. It is just like double-clicking.
  1. Go to the line that you want to delete in the editor
  2. Press the ESC key. (This is to make sure that you are in the command mode)
  3. Press dd to delete the line
Delete multiple lines in vi editor
If you know how many lines you want to delete ahead of time, then deleting multiple lines is just as easy as deleting a single line. You will prefix the dd command with the number of lines you want to remove.
  1. Go to the first line that you want to delete
  2. Press the ESC key
  3. Press the number of lines you want to delete, followed by dd (eg. 4dd or 25dd)
The lines that you want to remove should be in succession or consecutive.

Delete lines in a range in vi editor

You can delete lines with in a range, if you know the start and end line numbers. This is a similar case to the one we mentioned in the previous section. The general syntax for deleting a range of lines is:
:[start number],[end number]d
So, to delete all lines between the lines number 111 and 234, you will
  1. Hit ESC key
  2. type :111,234d
  3. Hit Enter

Delete all lines in vi editor

You can use the same syntax to delete all lines in the file. 
There are other ways to empty or truncate a file if you want to, but if you are already in the editor, then this will work just as well.
  1. Hit ESC key
  2. type :1,$d
  3. Hit Enter
The $ character denotes the last line in the file. So the above command will delete lines starting with the first line and ending with the last line.

delete all lines before the current line

Another variation of the range is to delete the lines before the cursor or the current line in the editor. The dot (.) character denotes the current line in the editor.
  1. Hit ESC key
  2. type :1,.-1d
  3. Hit Enter
The above command will remove all lines starting with the first line till the line before the current line.

Delete all lines after the current line

To delete lines after the current line, you can use the dot (.) to denote the current line and dollar ($) to denote the last line.
  1. Hit ESC key
  2. type :.+1,$d
  3. Hit Enter

Delete lines that match a pattern in vi editor

You can also do a search and delete, if you want to delete lines that contain certain words or character sequences. So, if you want to delete all lines in the file that contain the word ‘saloon‘, then
  1. Hit ESC key
  2. type :g/saloon/d
  3. Hit Enter

Delete lines that do not match the pattern

If you want to delete that do not match a specific pattern, then you will need to negate the match before deleting. So, to delete lines that do not have the word ‘saloon’, you will
  1. Hit ESC key
  2. type :v/saloon/d
  3. Hit Enter

Delete all blank lines in a file

To delete all blank lines in a file, you can use a variation of the pattern matching.
  1. Hit ESC key
  2. type :g/^$/d
  3. Hit Enter
Pattern matching in vi editor is a very powerful tool. If you make yourself familiar with the pattern matching commands in vi, then you can use it for all the various different text manipulation that you will come across.
Request: If you find this information useful, please provide your valuable comments.

Pylint in python/ Pylint score testing/ pylint package / Pylint Tutorial

pylint:
Pylint isn't smarter than you are: it may warn you about things that you have dedicated done.
Pylint tries hard to report as few false positives.

How to install pylint
==> Windows / OS X (MAC)     pip install pylint 
==> Ubuntu / Debian OS            sudo apt-get install pylint

from command prompt:
=================
python.exe -m pip install --upgrade pip
python -m pip install pylint

Utilization of pylint:
------------------------
==>  In terminal / command prompt go to the python file path.
==>  python -m pylint operators.py
==>  pylint  file_name.py  # this command will display  how much score your code rated.
                       or
        pylint directory/mymodule.py

Parallel pylint score validation : 
======================
It is possible to speed up the execution of Pylint.
If the running computer has more CPUs than one, then the work for checking all files could be spread across all cores via Pylints's sub-processes.
This functionality is exposed via the -j command-line parameter.
If the provided number is 0, then the total number of CPUs will be autodetected and used.

pylint -j 4 File_name1.py File_name2.py File_name3.py File_name4.py


This will spawn 4 parallel Pylint sub-process, where each provided module will be checked in parallel. Discovered problems by checkers are not displayed immediately. They are shown just after checking a module is complete.
There are some limitations in running checks in parallel in the current implementation. It is not possible to use custom plugins (i.e. --load-plugins option), nor it is not possible to use initialization hooks (i.e. the --init-hook option).

Exit codes

Pylint returns bit-encoded exit codes. If applicable, the table below lists the related stderr stream message output.
exit codemeaningstderr stream message
0no error
1fatal message issued
2error message issued
4warning message issued
8refactor message issued
16convention message issued
32usage error
  • "internal error while receiving resultsfrom child linter" "Error occurred, stopping the linter."
  • "<return of linter.help()>"
  • "Jobs number <#> should be greater than 0"

Thursday, January 23, 2020

Connect to Linux/Ubuntu based Remote desktop & execute commands on it using Python

Python  code useful for following :

==> Connect to remote desktop machine(Linux/ Ubuntu based systems) 
==> Copy the files to from local to remote machine 
==> Copy the files to from remote machine to local  machine
==>Executing commands on Remote machine from local machine
==>To take screenshot of remote machine

Note: I have used config.json file, for future modifications

{
  "modelName": "Desktop",
  "Local_Machine_Path": "C:\\Bhagyasree\\images\\",

  "Linux_Remote_Machine_Path": "/home/Narendra/ntest/",
  "Linux_Remote_Machine_IP_Addr": "192.10.14.3",
  "Linux_Remote_Machine_User_Name": "narendrab",
  "Linux_Remote_Machine_Pass_word": "Nanna@786",
}

ip_addr = Linux_Remote_Machine_IP_Addr
User_Name = Linux_Remote_Machine_User_Name
Pass_word = Linux_Remote_Machine_Pass_word
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
print("Please wait while connecting to host machine/Remote server")
ssh_client.connect(ip_addr, username=User_Name, password=Pass_word)
print("Please wait, executing command on remote machine")

remote_path = Linux_Remote_Machine_Path
local_path = Local_Machine_Path

path = Linux_Remote_Machine_Path
# image_name = "Desktop"

image_name = "Desktop"
cmd1 = "import -window root -display :0 " + path + "{}.png".format(image_name)
stdin, stdout, stderr = ssh_client.exec_command(cmd1)
host = Local_Machine_Path
target = Linux_Remote_Machine_Path
image_name = "Desktop.png"sftp = ssh_client.open_sftp()
sftp.get(target + image_name, host + image_name)
print("file successfully copied")
ssh_client.close()

How to install OpenSSL on CentOS?

How to install latest version of OpenSSL on CentOS?

Step 1:  mkdir Openssl
Step 2:  cd Openssl/
Step 3:  wget https://www.openssl.org/source/old/1.0.2/openssl-1.0.2t.tar.gz
Step 4:  tar -zxvf openssl-1.0.2t.tar.gz
Step 5:  cd openssl-1.0.2t/
Step 6:  ./config --prefix=/usr/ -fPIC -pthread -shared
Step 7:  make all
Step 8:  make install
Step 9:  openssl version