0

I'm trying to make a function, f(x), that would add a "-" between each letter:

For example:

f("James")

should output as:

J-a-m-e-s-

I would love it if you could use simple python functions as I am new to programming. Thanks in advance. Also, please use the "for" function because it is what I'm trying to learn.

Edit:

yes, I do want the "-" after the "s".

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
James
  • 49
  • 1
  • 6

6 Answers6

8

Can I try like this:

>>> def f(n):
...     return '-'.join(n)
...
>>> f('james')
'j-a-m-e-s'
>>>

Not really sure if you require the last 'hyphen'.

Edit:

Even if you want suffixed '-', then can do like

def f(n):
   return '-'.join(n) + '-'

As being learner, it is important to understand for your that "better to concat more than two strings in python" would be using str.join(iterable), whereas + operator is fine to append one string with another.

Please read following posts to explore further:

Community
  • 1
  • 1
James Sapam
  • 16,036
  • 12
  • 50
  • 73
  • I like your post as first post and added few more details as I notice OP is new, please check updated answer, if don't like then edit/revert. good luck. – Grijesh Chauhan Apr 01 '15 at 03:53
  • As of Python 2.6 (I think) it is actually faster to use ```+=``` then to use ```str.join()```. Sorry I forget the source, but feel free to ```timeit``` yourself. – pzp Apr 01 '15 at 04:02
  • @pzp1997 yes to add two strings `+=` would be better than `str.join` : check here: http://stackoverflow.com/questions/12169839/which-is-better-to-concat-a-string-in-python – Grijesh Chauhan Apr 01 '15 at 04:04
  • That was actually the source that I was referring to. And according to that ```+=``` is faster than ```str.join()``` in EVERY case. Even when concatenating 100,000 one hundred character strings += is faster (and I doubt anyone would ever reasonably need to do something that extreme). Part of the reason might be because it takes more time to resolve ```str.join()``` than ```+=```, which is an operator. – pzp Apr 01 '15 at 04:13
  • Then Pep8 needs to be updated: `Code should be written in a way that does not disadvantage other implementations of Python [snip]. For example, do not rely on CPython's efficient implementation of in-place string concatenation for statements in the form a += b or a = a + b. [snip] In performance sensitive parts of the library, the ''.join() form should be used instead.` – AChampion Apr 01 '15 at 04:40
5

Also, please use the "for" function because it is what I'm trying to learn

>>> def f(s):
        m = s[0]
        for i in s[1:]:
             m += '-' + i
        return m

>>> f("James")
'J-a-m-e-s'
  • m = s[0] character at the index 0 is assigned to the variable m

  • for i in s[1:]: iterate from the second character and

  • m += '-' + i append - + char to the variable m

  • Finally return the value of variable m

If you want - at the last then you could do like this.

>>> def f(s):
        m = ""
        for i in s:
            m +=  i + '-'
        return m

>>> f("James")
'J-a-m-e-s-'
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • "Because it is what **I'm trying to learn**," --- if someone trying to learn then posting an unexplained code is not that much helpful. You should tell why your code is not bad in Python -- (don't suggest C kindof code in Python) – Grijesh Chauhan Apr 01 '15 at 03:37
  • Avinash every code in computer runs in 0s and 1s form, how much internal you would like to tech him? I was just telling some obvious explanation this question and python. check @sapam's answer. – Grijesh Chauhan Apr 01 '15 at 03:58
  • anyways, your answer is good because OP specially request for "for" loop code. – Grijesh Chauhan Apr 01 '15 at 04:05
  • unnecessary to pop off the first list item because the OP wants a final -, so `for i in s: m += i + '-'` would achieve this. Though I'm not a great fan of string concatenation, strings are immutable so this can be expensive. – AChampion Apr 01 '15 at 04:35
2
text_list = [c+"-" for c in text]
text_strung = "".join(text_list)
Alexander R.
  • 1,756
  • 12
  • 19
1

Given you asked for a solution that uses for and a final -, simply iterate over the message and add the character and '-' to an intermediate list, then join it up. This avoids the use of string concatenations:

>>> def f(message)
        l = []
        for c in message:
            l.append(c)
            l.append('-')
        return "".join(l)
>>> print(f('James'))
J-a-m-e-s-
AChampion
  • 29,683
  • 4
  • 59
  • 75
1

As a function, takes a string as input.

def dashify(input):
    output = ""
    for ch in input:
        output = output + ch + "-"
    return output
MadMan2064
  • 436
  • 3
  • 4
0

I'm sorry, but I just have to take Alexander Ravikovich's answer a step further:

f = lambda text: "".join([c+"-" for c in text])

print(f('James'))  # J-a-m-e-s-

It is never too early to learn about list comprehension.

"".join(a_list) is self-explanatory: glueing elements of a list together with a string (empty string in this example).

lambda... well that's just a way to define a function in a line. Think

square = lambda x: x**2
square(2)  # returns 4
square(3)  # returns 9

Python is fun, it's not {enter-a-boring-programming-language-here}.

Community
  • 1
  • 1
frnhr
  • 12,354
  • 9
  • 63
  • 90