ocean.1234 ocean.1234 -4 years ago 130
Python Question

How to add strings to items in list that resulted from split?

I am building a function that accepts a string as input, splits it based on certain separator and ends on period. Essentially what I need to do is add certain pig latin words onto certain words within the string if they fit the criteria.

The criteria are:


if the word starts with a non-letter or contains no characters, do nothing to it

if the word starts with a vowel, add 'way' to the end

if the word starts with a consonant, place the first letter at the end and add 'ay'


For output example:


simple_pig_latin("i like this") → 'iway ikelay histay.'
--default sep(space) and end(dot)

simple_pig_latin("i like this", sep='.') → 'i like thisway.'
--separator is dot, so whole thing is a single “word”

simple_pig_latin("i.like.this",sep='.',end='!') → 'iway.ikelay.histay!'
--sep is '.' and end is '!'

simple_pig_latin(".") → '..'
--only word is '.', so do nothing to it and add a '.' to the end


My code is as follows but the issue is I am unsure of how to add the strings to the end of each item:

def simple_pig_latin(input, sep='', end='.'):
my_string=input()
my_string=my_string.split(sep)
new_string=""
Vowels= ('a','e','i','o','u')
Digit= (0,1,2,3,4,5,6,7,8,9)
cons=('b','c','d','f','g','h','j','k','l','m','n')+
('p','q','r','s','t','v','w','x','y','z')
for word in my_string:
if [i][0]==Vowels:
new_string=new_string+"way"
return
if [i][0]==Digit:
new_string=new_string+
return
if [i][0]==cons:
new_string=new_string+
else:
return
return new_string

Answer Source

You have the means of adding strings together correct: you use the + operator, as you have in new_string = new_string + "way".

You have two other major issues, however:

  1. To determine whether a variable can be found in a list (in your case, a tuple), you’d probably want to use the in operator. Instead of if [i][0]==Vowels: you would use if [i][0] in Vowels:.

  2. When you reconstruct the string with the new words, you will need to add the word to your new_string. Instead of new_string=new_string+"way" you might use new_string = word+"way". If you choose to do it this way, you’ll also need to decide when to add the sep back to each word.

Another way of joining smaller strings into larger ones with a known separator is to create a list of the new individual strings, and then join the strings back together using your known separator:

separator = ' '
words = sentence.split(separator)
newWords = []
for word in words:
    newWord = doSomething(word)
    newWords.append(newWord)

newSentence = separator.join(newWords)

In this way, you don’t have to worry about either the first or last word not needing a separator.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download