Home > database >  Adding a character in front of a list
Adding a character in front of a list

Time:03-22

To post a few hashtag on twitter I need to add # in font of the tags. The code:

s = ['Compile ', 'With ', 'Code'] 
print(*s, sep="\n#")

This code produces :

Compile 
#With 
#Code

However there is no hash character in front of the first element Compile. How can I add # in front of first element also?

CodePudding user response:

You can use list comprehensions, right?

output = ["#" x for x in s]
print(*output,sep='\n')

Returns:

#Compile 
#With 
#Code

Or in a single line:

print(*["#" x for x in s],sep='\n')

CodePudding user response:

You could also use the higher order function map to prepend the '#' symbol:

s = ["Compile ", "With ", "Code"]
result = map(lambda x: "#"   x, s)
print(*result, sep=" ")

CodePudding user response:

You can use join and list comprehension

s = ['Compile ', 'With ', 'Code']
s = ['#' word for word in s]     # Add hashtag symbol to each word
output = '\n'.join(s)            # Join hashtags using new-line character
print(output)

Result:

#Compile 
#With 
#Code
  • Related