Home > Blockchain >  How to get some string into single string
How to get some string into single string

Time:03-21

I would need some help, i write down my code and what i'd like to get, thanks.

text = ["Mayhem's neckwear is a STRING OF PEARLS"]
for line in text:
  line = line.split()
  for word in line:
    if word != "Mayhem's" and word.isupper():
      print(word)

Output :

STRING
OF
PEARLS

But i would like to output : STRINGOFPEARLS but not in other list or something like that. If you need further information let me know.

CodePudding user response:

You can use end = '' this will print it without new line.

text = ["Mayhem's neckwear is a STRING OF PEARLS"]
for line in text:
  line = line.split()
  for word in line:
    if word != "Mayhem's" and word.isupper():
      print(word, end = '')

CodePudding user response:

Well, what you're doing right now (in the last for loop) is iterating through every word.

After that, if it is not "Mayhem's" and is uppercase, then you're printing it. So, you're printing 'STRING', and then 'OF' and then 'PEARLS'.

Your question is a bit unclear: what do you want to do with the strings you get?

If you want to add these strings to a list, then you can do this:

text = ["Mayhem's neckwear is a STRING OF PEARLS"]
wordList = [] # list to hold words
for line in text:
  line = line.split()
  for word in line:
    if word != "Mayhem's" and word.isupper():
      wordList.append(word)
print(wordList) # prints your final list of words

If you want to combine these strings into a single string, then you can do this:

text = ["Mayhem's neckwear is a STRING OF PEARLS"]
wordList = []
for line in text:
  line = line.split()
  for word in line:
    if word != "Mayhem's" and word.isupper():
      wordList.append(word)
finalString = ' '.join(wordList) # this is what you get
print(finalString)

I hope this helped! If my answer doesn't do what you wanted it to, you can add a comment, I will update my answer.

  • Related