파이썬 python list to string 리스트를 문자열로 변경

파이썬에서 리스트 문자로 변경하는 방법에 대해 알아보겠습니다.
join 메서드를 이용하는 방법과 for문를 이용하여 배열을 문자열로 변경할 수 있습니다.
두 가지 방법을 비교해 보겠습니다.

  • join: 리스트의 모든 요소를 합쳐 하나의 문자열을 반환합니다.

- join

배열의 모든 요소를 합쳐 하나의 문자열을 반환합니다.
새로운 문자열을 반환합니다.

Syntax: separator.join(iterable)


list = ['a', 'b', 'c'] print(''.join(list)) # print: abc print(','.join(list)) # print: a,b,c

INFO: 지정된 구분자로 구분되어 모든 요소를 합친 새로운 문자열을 반환합니다.


list = ['1', 2, 3] print(','.join(list)) # print: TypeError: sequence item 1: expected string, int found

INFO: 배열안의 요소가 string 형이 아니면 에러가 발생한다.


list = ['1', 2, 3] print(','.join(str(e) for e in list)) # print: 1,2,3

INFO: join 메서드를 실행하기 전에 배열안의 요소를 string형으로 형 변환하여 예외처리 할 수 있다.



for문 사용

for문을 이용하여 리스트의 값을 문자열로 변경해보겠습니다.

list = ['a', 'b', 'c'] str = '' separtor = ',' for idx, val in enumerate(list): str += val + ('' if idx == len(list) -1 else separtor) print(str) # print: a,b,c

INFO: for문을 사용하면 join 함수 외에 enumerate, len, 삼항연산자 등으로 구현 해야하기 때문에 join 함수를 이용하는게 보기도 좋고 쉽다.


join 메서드, 배열의 요소를 구분자로 구분하여 하나의 문자열로 반환하는 함수에 대해 알아보았습니다.
태그 목록을 # 기호로 구분하여 표시하거나 시간에 대한 정보를 배열로 가지고있을 때(['02', '30', '24']) 유용하게 쓸 수 있을꺼 같습니다.


[Python] - 파이썬 python list 찾기

[Python] - 파이썬 python string, array, tuple length 길이

[Python] - 파이썬 python string to list 문자열을 리스트로

javascript 배열 안에서 원하는 값 또는 요소를 찾는 방법에 대해 알아보겠습니다.
배열안의 값을 찾는 법은 다양한 방법으로 구현할 수 있습니다.
찾는 값의 index번호를 알고 배열에서 바로 값을 가져오는 경우도 있고 값만 가지고 찾는 방법도 있습니다.
여러상황에서 사용하는 메서드를 알아보고 상황에 맞게 알맞은 방법을 사용하세요.

array[index]

배열의 값의 index번호를 알고 있으면 index값을 적용하여 값을 가져올 수 있습니다.

let array = ['apple', 'melon', 'grape', 'kiwi']; let found = array[1]; console.log(found); // output: melon found = array[3] console.log(found); // output: kiwi

array.indexOf

배열에서 지정된 값(요소)와 일치하는 첫 번째 인덱스 값을 반환합니다.
찾는 값이 존재하지 않으면 -1를 반환합니다.
기존 배열은 변경하지 않습니다.

Syntax: arr.indexOf(searchElement[, fromIndex])

  • searchElement: 배열에서 찾을 값
  • fromIndex: 검색을 시작할 index값 지정
let array = ['apple', 'melon', 'grape', 'kiwi', 123, "123"]; let found = array.indexOf('kiwi'); console.log(found); // output: 3 found = array.indexOf('kiw'); console.log(found); // output: -1 found = array[array.indexOf('kiwi')]; console.log(found); // output: kiwi found = array.indexOf('123'); console.log(found); // output: 5 found = array.indexOf(123); console.log(found); // output: 4

배열에서 찾고자 하는 값과 정확히 일치하는 값의 index 값을 반환합니다.

NOTE: indexOf 메서드는 변수의 타입까지 비교(===)하여 일치하는 요소를 찾습니다.
123, '123'의 값이 서로 다른 index를 반환합니다.


- array.find

배열에서 주어진 조건을 만족하는 첫 번째 값을 반환합니다.
만일 조건을 만족하지 못하면 undefined를 반환합니다.
기존 배열은 변경하지 않습니다.

Syntax: arr.find(callback(element[, index[, array]]) [, thisArg])

  • element: callback 함수에서 현재 처리하고 있는 배열의 값
  • index: 현재 처리하고 있는 배열의 index
  • array: 원본 array
let array = ['apple', 'melon', 'grape', 'kiwi']; let found = array.find(element => element == 'grape'); console.log(found); // output: grape array = [5, 9, 13, 20, 55]; found = array.find(element => element > 10); console.log(found); // output: 13

find 메서드는 조건을 만족하는 첫번째 값(요소)를 반환합니다.

INFO: 첫 번째 요소만 반환하기 떄문에 모든 요소를 찾으려면 다른 방법으로 구현해야합니다.


- array.findIndex

배열에서 주어진 조건을 만족하는 첫 번째 index 값을 반환합니다.
만일 조건을 만족하지 못하면 -1을 반환합니다.
기존 배열은 변경하지 않습니다.

Syntax: arr.findIndex(callback(element[, index[, array]])[, thisArg])

  • element: callback 함수에서 현재 처리하고 있는 배열의 값
  • index: 현재 처리하고 있는 배열의 index
  • array: 원본 array
let array = ['apple', 'melon', 'grape', 'kiwi']; let found = array.findIndex(element => element == 'grape'); console.log(found); // output: 2 array = [5, 9, 13, 20, 55]; found = array.findIndex(element => element > 10); console.log(found); // output: 2

findIndex 메서드는 조건을 만족하는 첫번째 index 값을 반환합니다.

INFO: find, findIndex 차이는 배열의 값을 반환하느냐 또는 배열의 index 값을 반환하느냐의 차이입니다.


- array.includes

배열에서 찾는 값(요소)를 포함하고 있는지 판단합니다.
찾고자 하는 값을 포함하고 있으면 true를 반환합니다.
찾고자 하는 값을 포함하고 있지 않으면 false를 반환합니다.

Syntax: arr.includes(valueToFind[, fromIndex])

  • valueToFind: 배열에서 찾을 값
  • fromIndex: 검색을 시작할 index값 지정
let array = ['apple', 'melon', 'grape', 'kiwi', 123]; let found = array.includes('grape'); console.log(found); // output: true found = array.includes('Grape'); console.log(found); // output: false found = array.includes('123'); console.log(found); // output: false

includes 메서드는 찾고자 하는 값이 배열에 존재하는지에 대한 결과를 반환합니다.

NOTE: 찾고자 하는 값이 문자나 문자열일 경우 includes는 대소문자를 구분합니다.
indexOf와 마찬가지로 변수의 타입까지 비교(===)하여 값의 존재 여부를 반환합니다.

[javascript] - 자바스크립트 javascript 문자열 찾기

[javascript] - 자바스크립트 javascript 문자열 공백 제거 trim

[javascript] - 자바스크립트 javascript string 길이 length

[javascript] - 자바스크립트 javascript 문자열 합치기

[javascript] - 자바스크립트 javascript 문자열 바꾸기 치환

[javascript] - 자바스크립트 javascript 문자열 추출 / 자르기



python 문자열 내장 함수에서 python 문자열 공백을 제거하는 함수에 대해 알아보겠습니다.

  • strip: 문자열의 시작과 끝의 공백을 제거합니다.
  • lstrip: 문자열의 시작의 공백을 제거합니다.
  • rstrip: 문자열의 끝의 공백을 제거합니다.

- strip

strip 메서드는 문자열의 양 끝의 공백을 모두 제거하는 메서드입니다.
새로운 문자열을 반환합니다.

Syntax: string.strip(characters)

txt = ' python ' print(txt.strip()) # print: python txt = ',.,.,,python?!?!?' print(txt.strip(',.?!')) # print: python

INFO: strip 메서드의 문자열 파라미터를 입력하면 문자열의 앞쪽과 뒤쪽에 일치하는 문자 모두 제거합니다.

- lstrip

lstrip 메서드는 문자열의 시작의 공백을 모두 제거하는 메서드입니다.
새로운 문자열을 반환합니다.

Syntax: string.lstrip(characters)

txt = ' python ' print(txt.lstrip()) # print: "python " txt = ',.,.,,python?!?!?' print(txt.lstrip(',.?!')) # print: python?!?!?

INFO: lstrip 메서드의 문자열 파라미터를 입력하면 문자열의 앞에서 일치하는 문자 모두 제거합니다.


- rstrip

rstrip 메서드는 문자열의 끝의 공백을 모두 제거하는 메서드입니다.
새로운 문자열을 반환합니다.

Syntax: string.rstrip(characters)

txt = ' python ' print(txt.rstrip()) # print: " python" txt = ',.,.,,python?!?!?' print(txt.rstrip(',.?!')) # print: ,.,.,,python

INFO: rstrip 메서드의 문자열 파라미터를 입력하면 문자열의 끝에서 일치하는 문자 모두 제거합니다.


[Python] - 파이썬 python string, array, tuple length 길이

[Python] - 파이썬 python 문자열 찾기

[Python] - [python] 파이썬 문자열 비교




python 객체(문자열 또는 배열, 튜플, ...)의 길이를 확인하는 방법에 대해 알아보겠습니다.

  • len: 객체의 길이를 반환하는 내장 함수 입니다.

- len

len 속성은 객체(배열, 문자열, 튜플, ...)의 길이를 반환합니다.

  • 문자열의 길이 구하기
txt = 'python' print(len(txt)) # print: 6 txt = ' python ' print(len(txt)) # print: 8

INFO: ' python '에서 볼 수 있듯이 공백도 포함한 길이를 반환합니다.

  • 배열의 길이 구하기
arr = ['python', 'is', 'so', 'good'] print(len(arr)) # print: 4

  • 튜플의 길이 구하기
arr = ('python', 'is', 'so', 'good') print(len(arr)) # print: 4

- len 활용

간단한 예제를 이용하여 len 메서드을 활용해보겠습니다.

str = 'python is so good' new_str = str[0:len(str)-1] print(new_str) # print: python is so goo

INFO: 문자열의 처음부터 맨 마지막 문자를 뺴고 끝까지 출력합니다.

str = 'python is so good' new_str = str[len(str)-1] print(new_str) # print: d

INFO: 문자열의 맨 마지막 위치에 있는 문자를 출력합니다.

str = 'python is so good' for index in range(len(str)): print(str[index]) # p # y # t # h # o # n # # i # s # # s # o # # g # o # o # d

INFO: 첫 문자부터 끝까지 한 글자씩 출력합니다.


자바스크립트 javascript 문자열 찾기

자바스크립트 문자열을 찾을 때 정규식을 사용하면 쉽게 문자열을 찾을 수 있습니다.
하지만 정규식 없이 문자열을 찾을 수 있는 메소드에 대해 알아보겠습니다.


- indexOf

indexOf() 메서드는 찾는 문자열이 대상 문자열 내에서 처음 발생하는 인덱스를 반환합니다.
값이 발견되지 않으면 -1을 반환한다.
indexOf()의 결과가 0 이상이면 찾는 문자열이 존재하는 것이다.

INFO: 찾는 문자열의 대소문자는 구분한다.

const str = 'Big golas get big results.'; console.log(str.indexOf('golas')); // output: 4 console.log(str.indexOf('Get')); // output: -1 console.log(str.indexOf('get') > -1); // output: true
  • array 배열에도 똑같이 적용할 수 있습니다.
  • 찾는 문자열이 존재할 경우 배열의 index값을 반환합니다.
const str = [ 'Big', 'golas', 'get', 'big', 'results.' ]; console.log(str.indexOf('golas')); // output: 1 console.log(str.indexOf('Get')); // output: -1 console.log(str.indexOf('get')); // output: 2

- includes

includes() 메서드는 찾는 문자열이 대상 문자열 내에서 존재하면 true 존재하지 않으면 false를 반환합니다.

TOOD:: 찾는 문자열의 대소문자는 구분한다.

const str = 'Big golas get big results.'; console.log(str.includes('golas')); // output: true console.log(str.includes('Get')); // output: false console.log(str.includes('get')); // output: true

- startsWith

startsWith() 메서드는 대상 문자열이 지정된 문자열로 시작하는지 판단합니다
지정된 문자열로 시작하면 true 그렇지 않으면 false를 반환합니다.

TOOD:: 찾는 문자열의 대소문자는 구분한다.

const str = 'Big golas get big results.'; console.log(str.startsWith('Big')); // output: true console.log(str.startsWith('Bigs')); // output: false console.log(str.startsWith('big')); // output: false

- endsWith

endsWith() 메서드는 대상 문자열이 지정된 문자열로 끝나는지 판단합니다
지정된 문자열로 끝나면 true 그렇지 않으면 false를 반환합니다.

**INFO: 찾는 문자열의 대소문자는 구분한다.

const str = 'Big golas get big results.'; console.log(str.endsWith('results.')); // output: true console.log(str.endsWith('results')); // output: false console.log(str.endsWith('ts.')); // output: true

[javascript] - 자바스크립트 javascript string 길이 length

[javascript] - 자바스크립트 javascript 문자열 공백 제거 trim

[javascript] - 자바스크립트 javascript 문자열 추출 slice, split, substr, substring

[javascript] - 자바스크립트 javascript 문자열 바꾸기 치환

[javascript] - 자바스크립트 javascript 문자열 합치기


javascript의 문자열 공백을 제거하는 방법에 대해 알아보겠습니다.
string 내장 함수를 이용하여 양 끝 또는 한 쪽의 공백을 제거할 수 있습니다.

- trim

trim() 메서드는 문자열 양 끝의 공백을 모두 제거하는 메서드 입니다.
모든 공백문자(space, tab, nbsp; 등)와 모든 개행문자(LF, CR)를 의미합니다.
새로운 문자열을 반환합니다.

**INFO:**양 끝의 공백을 제거합니다. 문자열 중간의 공백은 제거되지 않습니다.

const str = ' Hello World! '; console.log(str); // output: " Hello World! " console.log(str.trim()); // output: "Hello World!"

- trimStart / trimLetf

trimStart() / trimLetf() 메서드는 문자열의 시작부분에서 공백 문자를 모두 제거 합니다.
새로운 문자열을 반환합니다.

const str = ' Hello World! '; console.log(str); // output: " Hello World! " console.log(str.trimStart()); // output: "Hello World! " console.log(str.trimLeft()); // output: "Hello World! "

- trimEnd / trimRight

trimEnd() / trimRight() 메서드는 문자열의 끝에서 공백 문자를 모두 제거합니다.
새로운 문자열을 반환합니다.

const str = ' Hello World! '; console.log(str); // output: " Hello World! " console.log(str.trimEnd()); // output: " Hello World!" console.log(str.trimRight()); // output: " Hello World!"

자바스크립트 javascript string 길이 length

javascript string 길이 / 문자열 길이를 구하는 방법에 대해 알아보겠습니다.
javascript 문자열의 길이는 length 속성을 이용하여 구할 수 있습니다.

- length

length 속성은 문자열의 길이를 반환합니다.

const str = 'abcd' console.log(str.length); // output: 4 const str1 = ' ab cd ' console.log(str1.length); // output: 7

INFO: ' ab cd '에서 볼 수 있듯이 공백도 포함한 길이를 반환합니다.

- length 속성 활용

간단한 예제를 이용하여 length 속성을 활용해보겠습니다.

const str = 'abcd' console.log(str.slice(str.length - 2)); // output: cd

INFO: 문자열 길이의 맨 마지막 두번째 문자부터 끝까지 출력합니다.

const str = 'abcd' console.log(str.charAt(str.length - 1)); // output: d

INFO: 문자열의 맨 마지막 위치에 있는 문자를 출력합니다.

const str = 'abcd' for (let i=str.length-1; i>-1; i--) console.log(str.charAt(i)); // output: d // output: c // output: b // output: a

INFO: 문자열의 맨 마지막 위치의 문자부터 처음까지 차례로 출력합니다.

파이썬 python 문자열 찾기

파이썬 문자열 내장 함수에서 문자열을 찾는 함수에 대해 알아보겠습니다.

  • count: 찾는 문자열의 갯수를 반환합니다.
  • find: 찾는 문자열의 position 값을 반환합니다.
  • index: 찾는 문자열의 position 값을 반환합니다.
  • startswith: 대상 문자열이 지정된 문자열로 시작하는지 판단합니다.
  • endswith: 대상 문자열이 지정된 문자열로 끝나는지 판단합니다.

- count

대상 문자열에서 찾는 문자열의 갯수를 반환합니다.

txt = 'Hello, Hello, welcome to the python world.' print(txt.count('Hello')) # print: 2 print(txt.count('welcome')) # print: 1 print(txt.count('goodbye')) # print: 0

- find

대상 문자열에서 찾는 문자열의 position 값을 반환합니다.

txt = 'Hello, welcome to the python world.' print(txt.find('python')) # print: 22 print(txt.find('welcome')) # print: 7 print(txt.find('goodbye')) # print: -1

INFO: 문자열이 존재하지 않는 경우 -1 을 반환합니다.


- index

대상 문자열에서 찾는 문자열의 position 값을 반환합니다.

txt = 'Hello, welcome to the python world.' print(txt.index('python')) # print: 22 print(txt.index('welcome')) # print: 7 print(txt.index('goodbye')) # print: ValueError: substring not found

INFO: 문자열이 존재하지 않는 경우 ValueError를 반환합니다.
find와 index의 차이는 문자열을 찾지 못했을 경우
find는 -1 을 반환하고 index는 ValueError를 반환한다는 것입니다.

- startswith

대상 문자열에서 지정된 문자열로 시작하는지를 판단합니다.
맞으면 True 틀리면 False를 반환합니다.

txt = 'Hello, welcome to the python world.' print(txt.startswith('Hello')) # print: True print(txt.startswith('welcome')) # print: False

- endswith

startswith과 반대로 대상 문자열에서 지정된 문자열로 끝나는지를 판단합니다.
맞으면 True 틀리면 False를 반환합니다.

txt = 'Hello, welcome to the python world.' print(txt.endswith('world.')) # print: True print(txt.endswith('python')) # print: False

+ Recent posts