的作品是使用重複字符語法檢查一個字符串包含相同字符的另一種方法。下面是一個PyUnit測試的代碼片段,它演示瞭如何使用幾個不同的字符串來實現,它們都包含一些逗號。
# simple test
test_string = ","
self.assertTrue(test_string.strip() == "," * len(test_string.strip()),
"Simple test failed")
# Slightly more complex test by adding spaces before and after
test_string = " ,,,,, "
self.assertTrue(test_string.strip() == "," * len(test_string.strip()),
"Slightly more complex test failed")
# Add a different character other than the character we're checking for
test_string = " ,,,,,,,,,a "
self.assertFalse(test_string.strip() == "," * len(test_string.strip()),
"Test failed, expected comparison to be false")
# Add a space in the middle
test_string = " ,,,,, ,,,, "
self.assertFalse(test_string.strip() == "," * len(test_string.strip()),
"Test failed, expected embedded spaces comparison to be false")
# To address embedded spaces, we could fix the test_string
# and remove all spaces and then run the comparison again
fixed_test_string = "".join(test_string.split())
print("Fixed string contents: {}".format(fixed_test_string))
self.assertTrue(fixed_test_string.strip() == "," * len(fixed_test_string.strip()),
"Test failed, expected fixed_test_string comparison to be True")
使用'for'循環。 – Blender
所有你需要做的就是跟蹤最後一個字符並將其與當前循環進行比較,'return print(d [0])'也是無效的 –