How to display first 3 letters in a word, but replace the remainder of the word with "-" dashes in Python 3

Viewed 162

Lets say I have a word, and I only want to display the first three letters of the word. But the remaining last letters need to show a dash or an asterisk, etc.

For example, if we have the word javascript, then the output should display jav-------, pebbles should display as peb----, or instead of python, the output should display pyt---, etc.

Would str.replace(old, new) or str.replace(old, new, count) work in this case? If yes, then how?

Here is an example I did:

>>> p = "kotlin"

>>> p = p.replace(p[3:], "-")

>>> p

'kot-'
>>> 

The desired output would display kot---, however, although it does show the first 3 letters in the word, kot- only shows one dash in the end.

What could be another way to approach this?

4 Answers

You could make a for loop or even use len(p) to check how many letters are there, subtract 3 and then place the number of words after the first 3,

p = "kotlin"
p[:3]+"-"*(len(p)-3)

output

"kot---"

You can use string multiplication:

dashes = "-" * len(p[3:])
p = p[:3] + dashes
def display_dashes(string):
    dashed_string = "-"*len(string)
    return string[:3]+dashed_string[:len(dashed_string)-3]
display_dashes("kotlin")
#'kot---'

Or You can use str.ljust() function to solve this one line

display_dashes = lambda string :string[:3].ljust(len(string),'-')
display_dashes("kotlin")
#'kot---'
p = "kotlin"
x = 3
p[:x]+'-'*x

Output

'kot---'
Related