String in Python
String in Python
function"""
str = input("Enter a string: ")
counter = 0
for s in str:
counter = counter+1
print("Length of the input string is:", counter)
—--------------------------------------------------
Write a Python program to get a string made of the first 2 and last 2
characters of a given string. If the string length is less than 2, return the
empty string instead.
str = input("Enter a string: ")
if len(str)< 2:
print("invalid input")
else:
print(str[0:2]+str[-2:])
—---------------------------------------
"""Write a Python program to get a string from a given string where
all occurrences of its first char have been
changed to '$', except the first char itself."""
str1 = input("Enter a string: ")
char=str1[0]
str1=str1.replace(char,'$')
str1=char+str1[1:]
print(str1)
—-------------------------------------------------------------------------------------
Write a Python program to add 'ing' at the end of a given string (length
should be at least 3). If the given string already ends with 'ing', add 'ly'
instead. If the string length of the given string is less than 3, leave it
unchanged.
Sample String : 'abc'
Expected Result : 'abcing'
Sample String : 'string'
Expected Result : 'stringly'
str1=input("enter a string")
length = len(str1)
if length > 2:
if str1[-3:] == 'ing':
str1 += 'ly'
else:
str1 += 'ing'
print(str1)
—---------------------------------------------------------
Write a Python function that takes a list of words and return the longest
word and the length of the longest one.
Sample Output:
Longest word: Exercises
Length of the longest word: 9
max1 = len(i)
temp = i
# Driver Program
a = ["one", "two", "third", "four"]
longestLength(a)
—------------------------------------
Write a Python program to remove the nth index character from a nonempty
string.
def remove_char(str, n):
first_part = str[:n]
last_part = str[n+1:]
return first_part + last_part
print(remove_char('Python', 0))
print(remove_char('Python', 3))
print(remove_char('Python', 5))
—-------------------------------------
Write a Python program to change a given string to a newly string where
the first and last chars have been exchanged.
def change_sring(str1):
return str1[-1:] + str1[1:-1] + str1[:1]
print(change_sring('abcd'))
print(change_sring('12345'))
—----------------------------------------
Write a Python program to remove characters that have odd index values in
a given string.
def odd_values_string(str):
result = ""
for i in range(len(str)):
if i % 2 == 0:
result = result + str[i]
return result
print(odd_values_string('abcdef'))
print(odd_values_string('python'))