Programing

.join () 메소드는 정확히 무엇을합니까?

lottogame 2020. 5. 6. 20:49
반응형

.join () 메소드는 정확히 무엇을합니까?


나는 파이썬을 처음 접했고 .join()문자열을 연결하는 데 선호되는 방법이라는 것을 완전히 혼동했습니다 .

나는 시도했다 :

strid = repr(595)
print array.array('c', random.sample(string.ascii_letters, 20 - len(strid)))
    .tostring().join(strid)

다음과 같은 것을 얻었습니다.

5wlfgALGbXOahekxSs9wlfgALGbXOahekxSs5

왜 이렇게 작동합니까? 595만 자동으로 추가 할 수?


출력을주의 깊게 살펴보십시오.

5wlfgALGbXOahekxSs9wlfgALGbXOahekxSs5
^                 ^                 ^

원래 문자열의 "5", "9", "5"를 강조 표시했습니다. Python join()메소드는 문자열 메소드이며 문자열과 결합 항목 목록가져옵니다 . 더 간단한 예는 다음을 설명하는 데 도움이 될 수 있습니다.

>>> ",".join(["a", "b", "c"])
'a,b,c'

주어진 목록의 각 요소 사이에 ","가 삽입됩니다. 귀하의 경우, "목록"은 문자열 표현 "595"이며, 이는 목록 [ "5", "9", "5"]로 취급됩니다.

+대신 찾고있는 것으로 보입니다 .

print array.array('c', random.sample(string.ascii_letters, 20 - len(strid)))
.tostring() + strid

join반복 가능한 것을 인수로 취합니다. 일반적으로 목록입니다. 귀하의 경우 문제는 문자열 자체가 반복 가능하여 각 문자를 차례로 제공한다는 것입니다. 코드는 다음과 같이 분류됩니다.

"wlfgALGbXOahekxSs".join("595")

이것은 다음과 동일하게 작동합니다.

"wlfgALGbXOahekxSs".join(["5", "9", "5"])

따라서 문자열을 생성합니다.

"5wlfgALGbXOahekxSs9wlfgALGbXOahekxSs5"

반복 가능한 문자열은 파이썬에서 가장 혼란스러운 시작 문제 중 하나입니다.


문자열을 추가하려면 +기호로 연결 하십시오.

예 :

>>> a = "Hello, "
>>> b = "world"
>>> str = a + b
>>> print str
Hello, world

join문자열을 구분 기호와 함께 연결합니다. 구분 기호는 바로 앞에 배치 join됩니다. 예 :

>>> "-".join([a,b])
'Hello, -world'

Join은 문자열 목록을 매개 변수로 사용합니다.


join ()은 모든 목록 요소를 연결하기위한 것입니다. 두 개의 문자열 "+"만 연결하면 더 의미가 있습니다.

strid = repr(595)
print array.array('c', random.sample(string.ascii_letters, 20 - len(strid)))
    .tostring() + strid

To expand a bit more on what others are saying, if you wanted to use join to simply concatenate your two strings, you would do this:

strid = repr(595)
print ''.join([array.array('c', random.sample(string.ascii_letters, 20 - len(strid)))
    .tostring(), strid])

There is a good explanation of why it is costly to use + for concatenating a large number of strings here

Plus operator is perfectly fine solution to concatenate two Python strings. But if you keep adding more than two strings (n > 25) , you might want to think something else.

''.join([a, b, c]) trick is a performance optimization.


On providing this as input ,

li = ['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']
s = ";".join(li)
print(s)

Python returns this as output :

'server=mpilgrim;uid=sa;database=master;pwd=secret'

list = ["my", "name", "is", "kourosh"]   
" ".join(list)

If this is an input, using the JOIN method, we can add the distance between the words and also convert the list to the string.

This is Python output

'my name is kourosh'

"".join may be used to copy the string in a list to a variable

>>> myList = list("Hello World")
>>> myString = "".join(myList)
>>> print(myList)
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
>>> print(myString)
Hello World

참고URL : https://stackoverflow.com/questions/1876191/what-exactly-does-the-join-method-do

반응형