python 3.x에서는 string.replace ()가 더 이상 사용되지 않습니다. 이 작업을 수행하는 새로운 방법은 무엇입니까?
답변
답변
replace()
<class 'str'>
python3 의 방법입니다 .
>>> 'hello, world'.replace(',', ':')
'hello: world'
답변
파이썬 3의 replace () 메소드는 다음과 같이 간단하게 사용됩니다.
a = "This is the island of istanbul"
print (a.replace("is" , "was" , 3))
#3 is the maximum replacement that can be done in the string#
>>> Thwas was the wasland of istanbul
# Last substring 'is' in istanbul is not replaced by was because maximum of 3 has already been reached
답변
당신이 사용할 수있는 str.replace ()를 A와 체인 str.replace () . 같은 문자열이 'Testing PRI/Sec (#434242332;PP:432:133423846,335)'
있고 모든 '#',':',';','/'
부호 를로 바꾸고 싶다고 생각하십시오 '-'
. 이 방법으로 (일반적인 방법),
>>> str = 'Testing PRI/Sec (#434242332;PP:432:133423846,335)'
>>> str = str.replace('#', '-')
>>> str = str.replace(':', '-')
>>> str = str.replace(';', '-')
>>> str = str.replace('/', '-')
>>> str
'Testing PRI-Sec (-434242332-PP-432-133423846,335)'
또는이 방법 (chain of str.replace () )
>>> str = 'Testing PRI/Sec (#434242332;PP:432:133423846,335)'.replace('#', '-').replace(':', '-').replace(';', '-').replace('/', '-')
>>> str
'Testing PRI-Sec (-434242332-PP-432-133423846,335)'
답변
이 시도:
mystring = "This Is A String"
print(mystring.replace("String","Text"))
답변
참고로, 문자열 내에서 임의의 위치 고정 단어에 일부 문자를 추가 할 때 (예 : 접미사 -ly 를 추가하여 부사 형용사를 변경하는 경우 ) 가독성을 위해 줄 끝에 접미사를 넣을 수 있습니다. 이렇게하려면 split()
inside를 사용하십시오 replace()
.
s="The dog is large small"
ss=s.replace(s.split()[3],s.split()[3]+'ly')
ss
'The dog is largely small'
답변
ss = s.replace(s.split()[1], +s.split()[1] + 'gy')
# should have no plus after the comma --i.e.,
ss = s.replace(s.split()[1], s.split()[1] + 'gy')
